微调器在 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();
}
});
}
}
Spinner is not working. Here is my code:
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();
}
});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您犯的唯一错误是您设置了不同的事件侦听器。
侦听器
OnItemClickListener
用于ListView
。对于
Spinner
您必须设置 < code>OnItemSelectedListener ..尝试将
OnItemClickListener
替换为setOnItemSelectedListener
,如下所示:The only mistake you made is you have set different event listener..
The Listener
OnItemClickListener
is forListView
..For
Spinner
you have to setOnItemSelectedListener
..Try replacing
OnItemClickListener
tosetOnItemSelectedListener
like :问题出在这里,
尝试替换如下,
The problem is here,
Try replacing it as follows,
这是 oncreate() 方法中的问题:
您将结果分配给 spinner,它是此处的局部变量/引用。 main.spinner 类字段仍然为空。这就是为什么在calculate()方法中出现NullPointerException的原因。
将上面的行替换为:
Here is the problem in your oncreate() method:
You assign the result to spinner which is a local variable/reference here. main.spinner class field is still null. This is why you have NullPointerException in calculate() method.
Replace the line above with:
试试这个
查看此链接
Try this one
Check Out on this link