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(); } });