OnItemSelectedListener for Spinner that was added programmatically does not trigger

别等时光非礼了梦想. 提交于 2019-12-11 02:16:54

问题


I've got a spinner that opens programmatically. It pops up and appears to be working fine, but for some reason my OnItemSelectedListener does not trigger any of the events within it.

public class BeerConverter extends Activity {

    ArrayAdapter<CharSequence> adapter3;
    Spinner spinner03;


    @Override
    public void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        spinner03 = new Spinner(this);
        adapter3 = new ArrayAdapter<CharSequence> (this, android.R.layout.simple_spinner_item);
        adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

        spinner03.setAdapter(adapter3);

        spinner03.setOnItemSelectedListener(new MyOnItemSelectedListener3());
        adapter3.add("Stuff");
        spinner03.performClick();

        }

Then I create the listener as a nested class:

public class MyOnItemSelectedListener3 implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parentview, View v,int position, long id){
        curPos = position;
        Context context = getApplicationContext();
        CharSequence text = "Test text. If you see this, it means MyOnItemSelectedListener3 was called.";
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();

    }

    public void onNothingSelected(AdapterView<?> arg0) 
    {
        //do nothing
    }
};

So when I send the spinner03.performClick(); the Spinner pops up correctly, but when an item in the Spinner is selected, it just closes and does not call the OnItemSelectedListener. It looks like this person had the same problem a while back, but didn't ever end up posting the solution.


回答1:


As the comment thread above suggests, many if not all events related to a View will not behave as you expect if the View in question is not attached to a window. Do not use unattached Views to drive any sort of user interaction.




回答2:


I had the same problem. I fixed it by setting spinner visibility not "Gone".



来源:https://stackoverflow.com/questions/6635732/onitemselectedlistener-for-spinner-that-was-added-programmatically-does-not-trig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!