Android: setSelection having no effect on Spinner

前端 未结 11 1291
我在风中等你
我在风中等你 2020-11-27 05:24

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

11条回答
  •  余生分开走
    2020-11-27 05:52

    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();
    

提交回复
热议问题