skydoves / PowerSpinner

🌀 A lightweight dropdown popup spinner, fully customizable with an arrow and animations for Android.
Apache License 2.0
1.22k stars 116 forks source link

setOnSpinnerItemSelectedListener with adapter in java #64

Closed binu8051 closed 3 years ago

binu8051 commented 3 years ago

Hi, i am using this spinner and my code is below

List iconSpinnerItemss = new ArrayList<>(); iconSpinnerItemss.add(new IconSpinnerItem("View all", ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_map))); iconSpinnerItemss.add(new IconSpinnerItem("Rock", ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_map))); iconSpinnerItemss.add(new IconSpinnerItem("Rocks", ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_map))); iconSpinnerItemss.add(new IconSpinnerItem("Rocks1", ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_map))); iconSpinnerItemss.add(new IconSpinnerItem("Rocks2", ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_map))); iconSpinnerItemss.add(new IconSpinnerItem("Rock3", ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_map))); IconSpinnerAdapter iconSpinnerAdapters = new IconSpinnerAdapter(stonetype_viewdb); stonetype_viewdb.setSpinnerAdapter(iconSpinnerAdapters); stonetype_viewdb.setItems(iconSpinnerItemss); stonetype_viewdb.selectItemByIndex(0); stonetype_viewdb.setIsFocusable(true); stonetype_viewdb.setLifecycleOwner(this);

How to code for setOnSpinnerItemSelectedListener , while searching i found only kotlin code. can anyone help to code it to get the position of selected item. Thanks

skydoves commented 3 years ago

If you don't use a custom adapter, check the below codes.

powerSpinnerView.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener<String>() {
      @Override public void onItemSelected(int oldIndex, @Nullable String oldItem, int newIndex,
        String newItem) {

      }
    });
binu8051 commented 3 years ago

i already tried this, but got this error. java.lang.ClassCastException: com.skydoves.powerspinner.IconSpinnerItem cannot be cast to java.lang.String

binu8051 commented 3 years ago

Hi, Any solution?

skydoves commented 3 years ago

As you can infer from the exception, replace String to IconSpinnerItem.

powerSpinnerView.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener<IconSpinnerItem>() {
      @Override
      public void onItemSelected(int oldIndex, @Nullable IconSpinnerItem oldItem, int newIndex,
        IconSpinnerItem newItem) {

      }
    });
binu8051 commented 3 years ago

Thanks its worked. Btw i cant set app:spinner_popup_height="wrap_content" Getting error Cannot resolve symbol 'wrap_content'

skydoves commented 3 years ago

We can't use the wrap_content. It receives only the dimensional size like a 120dp. Thanks!