How to select first item of a spinner in a test

2019-06-18 23:23发布

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.

3条回答
Emotional °昔
2楼-- · 2019-06-18 23:37

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

查看更多
霸刀☆藐视天下
3楼-- · 2019-06-18 23:43

Look at the SpinnerTest sample application in the Developer Guide. It actually sends keystrokes to the activity.

查看更多
Fickle 薄情
4楼-- · 2019-06-18 23:53

Use

spinner.setSelection(0,true);

The second parameter will actually animate the selection to the 0 index.

查看更多
登录 后发表回答