开发者

OnItemSelectedListener for Spinner that was added programmatically does not trigger

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;
        Co开发者_运维知识库ntext 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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜