Android: setSelection having no effect on Spinner

前端 未结 11 1232
我在风中等你
我在风中等你 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:35

    I had the same problem with a spinner inside a fragment : setSelection works correctly during the onCreate at first start of the activity, but not when I rotate the screen. I solved it by calling setSelection within the onViewStateRestored method of the fragment instead of calling it inside the onCreate method. I'm not sure but I think that you can't use setSelection until the view is fully loaded, even if you can findViewById it.

    0 讨论(0)
  • 2020-11-27 05:40

    I had similar problem. In my case setAdaper and setSelection were in correct order! Executed form onCreate worked, but when executed from onResume had no effect.

    The solution is to call setSelection(my_pos, true). Notice the second parameter.

    0 讨论(0)
  • 2020-11-27 05:41

    None of the previous answers worked for me. What did work, though, was creating the instance variable mSpinner in the onCreateView() method of my fragment (or in the onCreate() method of your activity), then doing this in my onLoadFinished() method...

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        adapter.swapCursor(cursor);
        //mSpinner.setAdapter(adapter);
        mSpinner.setSelection(mSelectedIndex);
    }
    
    0 讨论(0)
  • 2020-11-27 05:41

    The solution is to call setSelection(my_pos, true). Notice the second parameter.

    Don`t forget, if you call animate, setup layout params then :) Example:

    LinearLayout.LayoutParams spinnerLp = (LinearLayout.LayoutParams) spinner.getLayoutParams();
    spinner.setSelection(selectedPositionAge, true);
    spinnerLp.gravity = Gravity.CENTER;
    spinner.setLayoutParams(spinnerLp);
    

    manually setted paddings to spinner needs to be reseted manually

    0 讨论(0)
  • 2020-11-27 05:50

    You might try

    mSpinner.post(new Runnable() {        
        public void run() {
          mSpinner.setSelection(1);
        }
      });
    

    this will post the runnable action to run as soon as the view is created

    0 讨论(0)
  • 2020-11-27 05:51

    Try moving the call to setSelection() after the call to setAdapter().

    0 讨论(0)
提交回复
热议问题