Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Spinner dropdown with selected item at top position

I have an issue with the Spinner in Android. Selecting an item from the dropdown will adjust the offset of that dropdown the next time it is opened. So for example if I choose item 100 in a 500 item dropdown, the next time I open the dropdown, item 100 will be at the top of the list. This is the behaviour I want.

There seems to be an issue when I combine the selector functionality with calling setSelection(int). With the following steps I seem to have broken the offset system on dropdown spinners.

  • Open the Spinner and select the second item.
  • Open the Spinner again and this time dismiss it without selecting anything.
  • Call setSelection(int) on the Spinner with a value greater than 2.
  • Open the Spinner a third time. Note that the offset is the same as back in Step 1.

I've taken a look at the code in Spinner and AdapterView, but I can't see anything public calls that I've missed. Is this a bug in Spinner or a bug in my code?

like image 917
Brad Avatar asked Jan 30 '13 04:01

Brad


2 Answers

Did you try public void setSelection (int position, boolean animate)? I haven't tried it, but I think passing true as the second parameter should make the list scroll to the selected position. The other alternative is to calculate the scroll offset (item height x selected item position) and call setDropDownVerticalOffset.

Update: I tried modifying the Spinner example in API demos to use setSelection(7, true) and it seems to work when following the 4 steps you provided in your question. I just added a Handler and modified showToast as follows:

private final Handler handler = new Handler();

void showToast(CharSequence msg) {
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    handler.postDelayed(new Runnable(){
        public void run() {
            Toast.makeText(Spinner1.this, "auto setting", Toast.LENGTH_SHORT).show();
            Spinner s2 = (Spinner) findViewById(R.id.spinner2);
            s2.setSelection(7, true);
        }
    }, 5000);
}

I tested as follows:

  1. open the second spinner and picking 'Venus' (the second selection).
  2. open the second spinner, then press back to dismiss
  3. after 5 seconds, the postDelayed call causes 'Neptune' (the seventh selection) to be selected
  4. open the spinner and the offset is correct
like image 109
ajh158 Avatar answered Oct 10 '22 22:10

ajh158


I think you can solve that problem with sending List to Adapter. When an item selected, sort your List then use notifyDataSetChanged() function of adapter. When you called setSelection(int) function again sort your List and use notifyDataSetChanged() function.

like image 43
Utkan Ozyurek Avatar answered Oct 10 '22 21:10

Utkan Ozyurek