我有一个Spinner使用自定义适配器,其中getView()被覆盖.我在捕获OnItemSelected事件时遇到问题,我认为该事件与自定义适配器有关.在我的onCreate()中,我有这个:
superGroupAdapter = new SuperGroupAdapter(context, R.layout.row_sg, sg_list);
sgSpinner.setAdapter(superGroupAdapter);
sgSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> adapterView, View view, int pos, long id) {
Log.d(Constants.TAG, "sg spinner on item selected");
}
@Override
public void onNothingSelected(AdapterView> adapterView) {
}
});
这是我的自定义适配器类:
public class SuperGroupAdapter extends ArrayAdapter {
@Inject SharedVisualElements sharedVisualElements;
Context context;
ArrayList sg_list;
public SuperGroupAdapter(Context context, int textViewResourceId, ArrayList sg_list) {
super(context, textViewResourceId, sg_list);
// add this line for any class that want to use any of the singleton objects
Injector.INSTANCE.getAppComponent().inject(this);
this.context = context;
this.sg_list = sg_list;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
parent.setBackgroundColor(sharedVisualElements.backgroundColor());
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.row_sg, parent, false);
TextView label = (TextView) row.findViewById(R.id.sg_name);
label.setText(sg_list.get(position));
label.setTypeface(sharedVisualElements.font());
label.setTextColor(sharedVisualElements.primaryFontColor());
label.setGravity(Gravity.CENTER_HORIZONTAL);
return row;
}
}
当活动初始化时,我看到日志输出
sg spinner on item selected
但这是我最后一次看到它.无论我从旋转器中选择一个项目多少次,它都不会再次发射.我一直在寻找一种陷阱的方法,但无济于事.有人可以帮忙吗?谢谢.
编辑
我还尝试更改类签名以实现OnItemSelected并将侦听器声明为单独的方法,如Android docs中所述,但得到了相同的结果.
我真的很茫然.我感谢任何帮助.
解决方法:
好吧,我想出来了.在查看了其他一些帖子后,我发现在我的测试数据中,我的微调器列表中只有一个项目. OnItemSelectedListener仅在您更改选择时触发.
来自OnItemSelectedListener的Android文档
This callback is invoked only when the newly selected position is
different from the previously selected position or if there was no
selected item.
因此,当活动初始化时,它选择了位置0处的项目.当我点击微调器并“选择”相同的项目时,此操作不会触发该事件.活到老,学到老.
标签:android-adapter,android,android-spinner
来源: https://codeday.me/bug/20190829/1763348.html