我需要在AlertDialog
中选择第二项时显示Spinner
。我知道使用onItemSelected
我们可以听到微调器选择&显示一个弹出窗口。问题是当我选择第二个项目时,会出现对话框,但在关闭对话框后再次选择相同的项目时,它不会显示对话框,因为onItemSelected
将不会被调用。这有什么解决方法吗?不使用自定义Spinner
实现。
答案 0 :(得分:3)
创建自定义微调器
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
public class CustomSpinner extends Spinner {
OnItemSelectedListener listener;
private AdapterView<?> lastParent;
private View lastView;
private long lastId;
public CustomSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
initlistner();
}
@Override
public void setSelection(int position) {
if (position == getSelectedItemPosition() && listener != null) {
listener.onItemSelected(lastParent, lastView, position, lastId);
} else {
super.setSelection(position);
}
}
private void initlistner() {
// TODO Auto-generated method stub
super.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
lastParent = parent;
lastView = view;
lastId = id;
if (listener != null) {
listener.onItemSelected(parent, view, position, id);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onNothingSelected(parent);
}
}
});
}
public void setOnItemSelectedEvenIfUnchangedListener(
OnItemSelectedListener listener) {
this.listener = listener;
}
}
设置监听器
private OnItemSelectedListener listener;
listener = new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
将侦听器对象传递给自定义侦听器
cusSpinner.setOnItemSelectedEvenIfUnchangedListener(listener);
答案 1 :(得分:-3)
尝试下面的代码:
spinner.setOnItemSelectedListener(this);
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch(arg2)
{
case 0:
{
Dialog dialog = new Dialog(getApplicationContext());
.......
dialog.show();
spinner.setSelection(0);
}
break;
}
[...]