Reputation: 9223
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.
setSelection(int)
on the Spinner with a value greater than 2. 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?
Upvotes: 7
Views: 4115
Reputation: 1467
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:
Upvotes: 2
Reputation: 638
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.
Upvotes: 1