From 8617ceea0524f8c05631f92879c85351fda5f454 Mon Sep 17 00:00:00 2001 From: Shahram Javadi Date: Fri, 10 Apr 2020 16:44:59 +0430 Subject: [PATCH] Enable OnItemSelectedListner for setSelectedIndex method --- .../materialspinner/example/MainActivity.java | 5 +++++ .../materialspinner/MaterialSpinner.java | 21 ++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/demo/src/main/java/com/jaredrummler/materialspinner/example/MainActivity.java b/demo/src/main/java/com/jaredrummler/materialspinner/example/MainActivity.java index 7b2cdf5..2532f88 100644 --- a/demo/src/main/java/com/jaredrummler/materialspinner/example/MainActivity.java +++ b/demo/src/main/java/com/jaredrummler/materialspinner/example/MainActivity.java @@ -65,12 +65,17 @@ public class MainActivity extends AppCompatActivity { MaterialSpinner spinner = (MaterialSpinner) findViewById(R.id.spinner); spinner.setItems(ANDROID_VERSIONS); + spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() { @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) { Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show(); } }); + + // if listener enabled is true You must declare it after setOnItemSelectedListener() + spinner.setSelectedIndex(0,true); + spinner.setOnNothingSelectedListener(new MaterialSpinner.OnNothingSelectedListener() { @Override public void onNothingSelected(MaterialSpinner spinner) { diff --git a/library/src/main/java/com/jaredrummler/materialspinner/MaterialSpinner.java b/library/src/main/java/com/jaredrummler/materialspinner/MaterialSpinner.java index 106ca23..58d0412 100755 --- a/library/src/main/java/com/jaredrummler/materialspinner/MaterialSpinner.java +++ b/library/src/main/java/com/jaredrummler/materialspinner/MaterialSpinner.java @@ -359,13 +359,32 @@ public int getSelectedIndex() { * Set the default spinner item using its index * * @param position the item's position + * @param listenerEnabled if user set true then listener enable at the first user must declare it after + * setItemSelectedListener and if that is false then itemSelectedListener not enabled at the first */ - public void setSelectedIndex(int position) { + public void setSelectedIndex(int position,boolean listenerEnabled) { if (adapter != null) { if (position >= 0 && position <= adapter.getCount()) { adapter.notifyItemSelected(position); selectedIndex = position; setText(adapter.get(position).toString()); + + if(listenerEnabled) + { + + if(onItemSelectedListener != null) + { + + onItemSelectedListener.onItemSelected(MaterialSpinner.this, position,getId(),adapter.get(position)); + } + + else { + + throw new IllegalStateException("Make listenerEnabled false or declare setSelectedIndex() after setOnItemSelectedListener()"); + } + + } + } else { throw new IllegalArgumentException("Position must be lower than adapter count!"); }