Android 为什么spinner中的onNothingSelected未被调用?
我有一个Android微调器,我想在微调器的选择面板显示时,当用户按下“后退键”时侦听事件。我已经实现了OnItemSelectedListener,但按下后退键时未调用onNothingSelected(AdapterView arg0)。Android 为什么spinner中的onNothingSelected未被调用?,android,spinner,Android,Spinner,我有一个Android微调器,我想在微调器的选择面板显示时,当用户按下“后退键”时侦听事件。我已经实现了OnItemSelectedListener,但按下后退键时未调用onNothingSelected(AdapterView arg0)。 我只想在用户不选择任何内容(或选择面板消失)时收听事件。 有没有正确的方法可以做到这一点 谢谢 Spinner s1=(Spinner)findViewById(R.id.Spinner 1); ArrayAdapter=ArrayAdapter.cre
我只想在用户不选择任何内容(或选择面板消失)时收听事件。
有没有正确的方法可以做到这一点 谢谢
Spinner s1=(Spinner)findViewById(R.id.Spinner 1);
ArrayAdapter=ArrayAdapter.createFromResource(
这个,R.array.colors,android.R.layout.simple\u微调器\u项);
setDropDownViewResource(android.R.layout.simple\u微调器\u下拉菜单\u项);
s1.设置适配器(适配器);
s1.setOnItemSelectedListener(
新建MSelectedListener(){
公营部门选举(
AdapterView父级、视图、整型位置、长id){
showToast(“喷丝头1:position=“+position+”id=“+id”);
}
未选择公共无效(AdapterView父级){
showToast(“喷丝头1:未选择”);
}
});
这是Android 2.2 SDK中的一个示例,当选择面板消失时,它也不会显示“Spinner1:unselected”。如果不扩展
Spinner
类,您似乎无法完成所需的操作。似乎微调器
没有将OnCancelListener
注册到为显示项目而生成的警报对话框
代码来源:
另外,setSelection
仅在单击对话框中的项目时调用。当用户按下后退按钮时,不会调用此函数,因为这是一个OnCancel
事件
扩展
Spinner
会有点麻烦,因为您必须将所有内容从android源代码复制回AdapterView
到源代码中,因为实现所需的各种成员字段仅在包级别公开。另一种方法是创建一个最小的自定义Spinner下拉项,即:
<com.mypackage.MyTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
/>
如果使用自定义ArrayAdapter仅设置一个下拉项进行回调,以及设置
回调的合适上下文等
根据您在回调中的操作,您可能希望
将其作为runnable发布,以便完全清理微调器
在它做任何事情之前。衷心感谢Qberticus!现在看来这是唯一的解决办法。@Qberticus我想我不明白什么时候叫onNothingSelect?如果现在选择“无”,那么什么时候?
@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;
}
<com.mypackage.MyTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
/>
public class MyTextView extends TextView {
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// Callback here
}
}