I\'m having some problem with setSelection on a Spinner. I set the value to be pre-selected when the spinner is shown in code, but it has no effect and the first alternative
In my case none of the answers worked, so I queued the setSelection through a Handler
new Handler().postDelayed(new Runnable() {
public void run() {
mSpinner.setSelection(1);
}
}, 100);
Doing this could cause problems when running on slow devices, but I'm working for a specific device so it's ok to use this hack
use this
sp2.setAdapter(sp2.getAdapter());
sp2.getAdapter().notifyDataSetChanged();
sp2.setSelection(0, false);
Spinner.setSelection()
do not work if you call it before Spinner.setAdapter()
Try calling setSelection()
after the call to setAdapter().
Reason Behind this : when you call Spinner.Selection()
before setting an adapter to it simply means that you are trying to set spinner to custom index by setSelection() when it doesn't contain any data or we can say thats spinner has max item =0.
so setSelection(1)
means setting index to 1 for spinner which has max item =0; Although spinner itself handles this outofBoundIndex so your app does not crashes.
call to SetSelection()
should be after setAdapter() only
Also if you have a Spinner.SetOnItemSelectedListener()
and you have problem that onItemSelected(AdapterView<?> parent, View view, int position, long id)
is tiggered with position value=0 when activity load and then you should use this pattern.
Spinner.SetAdapter()
Spinner.setSelection();
Spinner.setOnItemSelectedListener();
try this, it worked for me:
Spinner destSpinner = (Spinner)dialogView.findViewById(R.id.edit_event_destination);
destSpinner.setSelection(0);
String dest = events.get(pos).getDestination();
int routesPos = routes.indexOf(dest);
destSpinner.setAdapter(aa);
Log.d(TAG, "Dest: " + dest + ", pos: " + routesPos);
destSpinner.setSelection(routesPos);
Sometimes, we may not set listeners because the spinner may be set to a certain value, and disabled as per requirement.
This can lead to setSelection() not selecting a value, since it needs a listener.
Make sure that the Spinner's setOnItemSelectedListener() is set to a custom listener like below.
Even if spinner is disabled, we must set a listener like below, so that setSelection() method works.
spinnerListener.setOnItemSelectedListener(spinnerListener);
AdapterView.OnItemSelectedListener spinnerListener = new
AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
//Your code
}
}
spinnerListener.setSelection(0);