gpt4 book ai didi

java - 如何在 Android 上的 Spinner 中使用 itemClickListener

转载 作者:行者123 更新时间:2023-12-02 01:44:37 27 4
gpt4 key购买 nike

在我的应用程序中,我有一个 Spinner,我应该将来自服务器的一些数据显示到此 Spinner 中。
我的服务器数据有:

"sections": [{
"id": 1,
"name": "Item 1"
}, {
"id": 2,
"name": "Item 2"
}, {
"id": 3,
"name": "Item 3"
}]

对于这个spinner,我应该设置默认文本以供首次显示以及当用户点击spinners < strong>项目显示此项目而不是默认文本。

为此,我编写了以下代码,但我不知道如何将 clickListener 设置为此项目以获取每个项目的 id!

我的适配器代码:

public class DashboardSupportSectionAdapter extends ArrayAdapter<Section> {

Context context;
List<Section> model;
String firstElement;
boolean isFirstTime;

public DashboardSupportSectionAdapter(Context context, int textViewResourceId, List<Section> model, String defaultText) {
super(context, textViewResourceId, model);
this.context = context;
this.model = model;
this.isFirstTime = true;
setDefaultText(defaultText);
}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (isFirstTime) {
model.get(0).setName(firstElement);
isFirstTime = false;
}
return getCustomView(position, convertView, parent);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
notifyDataSetChanged();
return getCustomView(position, convertView, parent);
}

public void setDefaultText(String defaultText) {
this.firstElement = model.get(0).getName();
model.get(0).setName(defaultText);
}

public View getCustomView(final int position, View convertView, ViewGroup parent) {

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.row_dashboard_support_section, parent, false);
TextView label = row.findViewById(R.id.spinner_text);
label.setText(model.get(position).getName());

return row;
}

}

我的 Activity 代码:

public class DashboardCreateSupportActivity extends BaseActivity {

@BindView(R.id.dashboardCreateSupport_sectionSpinner)
Spinner dashboardCreateSupport_sectionSpinner;
String defaultTextForSpinner = "Select section";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard_create_support);

ButterKnife.bind(this);

dashboardCreateSupport_sectionSpinner.setAdapter(new DashboardSupportSectionAdapter(this, R.layout.row_dashboard_support_section,
Constants.supportListResponse.getRes().getSections(), defaultTextForSpinner));

}
}

我希望当点击每个项目时,在toast消息中显示项目的ID。

我怎样才能做到?

最佳答案

dashboardCreateSupport_sectionSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Constants.supportListResponse.getRes().getSections().get(position).getId();
}
});

关于java - 如何在 Android 上的 Spinner 中使用 itemClickListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53868702/

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