gpt4 book ai didi

android - Spinner OnItemSelected 使用自定义适配器

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:25 25 4
gpt4 key购买 nike

我有一个 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<String> {

@Inject SharedVisualElements sharedVisualElements;

Context context;
ArrayList<String> sg_list;

public SuperGroupAdapter(Context context, int textViewResourceId, ArrayList<String> 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;
}
}

Activity 初始化时,我看到日志输出

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.

因此,当 Activity 初始化时,它选择了位置 0 处的项目。当我点击微调器并“选择”同一项目时,此操作不会触发该事件。活到老,学到老。

关于android - Spinner OnItemSelected 使用自定义适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32530404/

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