Spinner item gets automatically selected upon entering activity. How do I avoid this?

后端 未结 8 1817
抹茶落季
抹茶落季 2020-12-18 20:04

I have a spinner in my Android app, and its onItemSelected() event automatically gets triggered upon entering the activity.

How do I avoid this?

8条回答
  •  余生分开走
    2020-12-18 21:02

    Well, you can add a dummy selection to the initial adapter, and ignore position number in the setOnItemSelectedListener. It's not pretty but it works. See this code for setting up the items for an array adapter.

    List names = new ArrayList();
    names.add("");
    names.addAll(realValues);
    

    Then in your setOnItemSelectedListener you can do this:

        @Override
        public void onItemSelected(AdapterView parent, View view, int position, long id)
        {
            if (position > 0)
            {
                String name = names.get(position - 1);
            }
            else
            {
                Log.d(TAG, "selected nothing or perhaps the dummy value");
            }
        }
    

提交回复
热议问题