Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable OnItemSelectedListner for setSelectedIndex method #138

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>() {

@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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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!");
}
Expand Down