如何在AutoCompleteTextView中关联JSON的id_county与county并获取选中ID
解决AutoCompleteTextView关联county与id_county并获取选中项ID的问题
方案1:修改实体类toString方法(简单快捷)
不需要额外自定义Adapter,只需在ListCounty类中重写toString()方法,让它返回要显示的county文本:
public class ListCounty { private String county; private String id_county; private String id_state; // 构造函数、getter、setter方法省略 @Override public String toString() { return county; // 返回AutoCompleteTextView中要显示的文本 } }
修改Adapter初始化代码,直接使用原始的ArrayList<ListCounty>作为数据源:
ArrayList<ListCounty> data = (ArrayList<ListCounty>) response.body().getListCounty(); AutoCompleteTextView countyEditText = findViewById(R.id.countyEditText); ArrayAdapter<ListCounty> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, data); // 直接传入ListCounty列表 countyEditText.setAdapter(adapter);
修改点击事件,直接获取选中的ListCounty对象,进而拿到对应的id_county:
countyEditText.setOnItemClickListener((parent, view, position, id) -> { ListCounty selectedCounty = (ListCounty) parent.getItemAtPosition(position); String selectedCountyName = selectedCounty.getCounty(); String selectedCountyId = selectedCounty.getIdCounty(); Log.d("APIhouse gson", "选中的县名:" + selectedCountyName); Log.d("APIhouse gson", "对应的ID:" + selectedCountyId); });
方案2:自定义Adapter(更灵活,适配复杂布局)
如果不想修改实体类的toString()方法,可以自定义Adapter控制显示内容:
- 创建自定义布局
item_county.xml(放在res/layout目录下):
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tv_county_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:textSize="16sp"/>
- 自定义Adapter类:
public class CountyAdapter extends ArrayAdapter<ListCounty> { public CountyAdapter(Context context, ArrayList<ListCounty> counties) { super(context, 0, counties); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_county, parent, false); } ListCounty county = getItem(position); TextView tvCountyName = convertView.findViewById(R.id.tv_county_name); tvCountyName.setText(county.getCounty()); return convertView; } }
- 初始化Adapter并设置到AutoCompleteTextView:
ArrayList<ListCounty> data = (ArrayList<ListCounty>) response.body().getListCounty(); AutoCompleteTextView countyEditText = findViewById(R.id.countyEditText); CountyAdapter adapter = new CountyAdapter(MainActivity.this, data); countyEditText.setAdapter(adapter);
- 点击事件逻辑和方案1一致,直接获取
ListCounty对象即可拿到id_county。
内容的提问来源于stack exchange,提问作者Stefano
相关产品推荐
相关产品推荐

