How to select first item of a spinner in a test
Solution 1
Use
spinner.setSelection(0,true);
The second parameter will actually animate the selection to the 0 index.
Solution 2
more "transparent" way:
Spinner.setSelection(Adapter.NO_SELECTION, false);**
*second argument is for selection animation
**this should be called after:
Spinner.setAdapter(...);
or any kind of methods that is involving Spinner.setSelection() for example :
Adapter.notifyDataSetChanged();
& for OnItemSelectedListener() not to fire up
Roland
Trying not to be religious over techical choices and therefore always trying to learn things where my knowleadgemap has its white areas, instead of increasing the resolution. Therefore I know both Java and .Net and some other stuff too.
Updated on June 14, 2022Comments
-
Roland about 2 years
I have a tests where I test an OnItemSelectedListener on a Spinner. It works great when testing items that is > 0. But it seems like I can't test the first item.
My current implementation that works if I select items with index > 0 looks like this.
final Addpointer addPointer = getActivity(); addPointer.runOnUiThread(new Runnable() { @Override public void run() { EditText address = (EditText) addPointer.findViewById(R.id.address); address.setText("a"); Spinner spinner = (Spinner) addPointer.findViewById(R.id.intOrHex); spinner.setSelection(0); View view = (View) spinner.getChildAt(0); long id = spinner.getAdapter().getItemId(0); spinner.performItemClick(view, 0, id); } });
What do I need to do to get the test to "select" the first item?
Thanks in advance
Roland
Answer: 1) Rahul garg about setting "animate" was the key to solve the problem. 2) But you can't trigger onSelectionChanged unless the selection actually changed (0 was initial state so I needed to set it to one before I set it back to zero.
-
Roland over 12 yearsNo, my OnClickListener doesn't recive a call with animate set to true
-
Roland over 12 yearsI was wrong above. But I needed to set selection to one, then setup the textfield and then set it to zero. Apparently one can't trigger the OnSelectionChanged to the same number it already is.
-
x-ray over 7 yearsThis is great! I added
Spinner.setSelection(Adapter.NO_SELECTION, false);
inonCreate
, after referencing the spinner with Butter Knife. I also registered the spinner callback with Butter Knife. Now the callback gets called once (and only once) after activity-(re-)creation, regardless of which item is selected. This is the behaviour I need.