gpt4 book ai didi

安卓微调器 : onItemSelected listener is not called when selecting the same item

转载 作者:行者123 更新时间:2023-12-04 18:03:07 25 4
gpt4 key购买 nike

我需要在 Spinner 中选择第二个项目时显示 AlertDialog。我知道使用 onItemSelected 我们可以收听微调器选择并显示弹出窗口。问题是当我选择第二个项目时,对话框出现,但在关闭对话框然后我们再次选择相同的项目后,它不会显示对话框,因为 onItemSelected 不会被调用。有什么解决方法吗?不使用自定义 Spinner 实现。

最佳答案

创建自定义微调器

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);

关于安卓微调器 : onItemSelected listener is not called when selecting the same item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31742895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com