我创建了一个微调器,当有人使用阵列适配器添加设备时,它会自动更新设备名称。 I created an OnItemSelected method with the spinner so when one of the names in the spinner is selected, a new window appears.但是,当 Activity 开始时,OnItemSelected 会自动选择列表中的第一项,因此在新窗口出现之前,用户没有机会实际进行选择。
代码如下:
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
startActivity(new Intent("com.lukeorpin.theappliancekeeper.APPLIANCESELECTED"));
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
有谁知道列表中的第一项不会被自动选中的方法吗?
这是微调器其余部分的代码:
ArrayAdapter<String> appliancenameadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, ApplianceNames); //Sets up an array adapter containing the values of the ApplianceNames string array
applianceName = (Spinner) findViewById(R.id.spinner_name); //Gives the spinner in the xml layout a variable name
applianceName.setAdapter(appliancenameadapter); //Adds the contents of the array adapter into the spinner
applianceName.setOnItemSelectedListener(this);
最佳答案
如果您试图避免初始调用监听器的 onItemSelected()
方法,另一种选择是使用 post()
来利用 View 的消息队列.微调器第一次检查您的监听器时,它尚未设置。
// Set initial selection
spinner.setSelection(position);
// Post to avoid initial invocation
spinner.post(new Runnable() {
@Override public void run() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Only called when the user changes the selection
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
});
关于java - 如何使 On Item Selected 不自动选择第一个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132971/