微调不工作在Android

微调不工作。 这是我的代码:

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

Solutions Collecting From Web of "微调不工作在Android"

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

监听器OnItemClickListener用于ListView ..

对于Spinner你必须设置OnItemSelectedListener ..

尝试将OnItemClickListenerreplace为OnItemSelectedListener如:

 spin.OnItemSelectedListener (new OnItemSelectedListener() { 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(); } }); 

这是你的oncreate()方法中的问题:

 spin = (Spinner) findViewById(R.id.spin); 

您将结果分配给微调器,这是一个局部variables/参考。 main.spinner类字段仍为null。 这就是为什么你在calculate()方法中有NullPointerException。

将上面的行replace为:

 this.spin = (Spinner) findViewById(R.id.spin); ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item,androidBooks); spin.setAdapter(adapter); 

问题在这里,

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

尝试更换它如下,

  spin.OnItemSelectedListener (new OnItemSelectListener() { public void onItemSelect(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(); } });