Spinner在android中不起作用

前端之家收集整理的这篇文章主要介绍了Spinner在android中不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Spinner无法正常工作.这是我的代码
public class second extends Activity{   
    Spinner spin;
    String[] str;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);        
        spin = (Spinner) findViewById(R.id.spin);
        str = new String[] {"bike","car"};      
        spin.setAdapter(new ArrayAdapter<CharSequence>(this,android.R.layout.simple_dropdown_item_1line,str));    

        spin.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> adapter,View view,int pos,long id) {
            // TODO Auto-generated method stub

            String data= spin.getItemAtPosition(pos).toString();
            Toast.makeText(second.this,data,Toast.LENGTH_SHORT).show();
               }    
        });
    }
}

解决方法

你犯的唯一错误是你设置了不同的事件监听器..

Listener OnItemClickListener适用于ListView ..

对于Spinner,你必须设置OnItemSelectedListener ..

尝试将OnItemClickListener替换为OnItemSelectedListener,如:

spin.OnItemSelectedListener (new OnItemSelectedListener() {

    public void onItemClick(AdapterView<?> adapter,long id) {
        // TODO Auto-generated method stub

        String data= spin.getItemAtPosition(pos).toString();
        Toast.makeText(second.this,Toast.LENGTH_SHORT).show();
    }

});
原文链接:https://www.f2er.com/android/317229.html

猜你在找的Android相关文章