我有一个 Android 微调器,我想在微调器的选择面板显示时用户按下“后退键”时监听事件。我已经实现了 OnItemSelectedListener ,但是当按下返回时没有调用 onNothingSelected(AdapterView arg0)键。
我只想在用户什么都不选择(或选择面板消失)时监听事件。
有正确的方法吗?
谢谢!
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.colors, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
showToast("Spinner1: position=" + position + " id=" + id);
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Spinner1: unselected");
}
});
This is a sample in Android 2.2 SDK,it's also not show "Spinner1: unselected"when the select panel disappear.
最佳答案
看起来如果不扩展 Spinner
类,您将无法做您想做的事。 Spinner
似乎没有向它构建的用于显示项目的 AlertDialog
注册 OnCancelListener
。
代码来自 Spinner.java :
@Override
public boolean performClick() {
boolean handled = super.performClick();
if (!handled) {
handled = true;
Context context = getContext();
final DropDownAdapter adapter = new DropDownAdapter(getAdapter());
AlertDialog.Builder builder = new AlertDialog.Builder(context);
if (mPrompt != null) {
builder.setTitle(mPrompt);
}
mPopup = builder.setSingleChoiceItems(adapter, getSelectedItemPosition(), this).show();
}
return handled;
}
public void onClick(DialogInterface dialog, int which) {
setSelection(which);
dialog.dismiss();
mPopup = null;
}
此外,setSelection
仅在单击对话框中的项目时调用。当用户按下后退按钮时不会调用此方法,因为这是一个 OnCancel
事件。
扩展 Spinner
会有点痛苦,因为您必须将所有内容从 android 源复制回 AdapterView
到您的源中,因为实现所需的各种成员字段是仅在包级别公开。
关于android - 为什么没有调用微调器中的 onNothingSelected?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3474029/