gpt4 book ai didi

java - 如何在 Spinner 中从 JSON 获取所选项目 id?

转载 作者:行者123 更新时间:2023-12-02 09:46:36 27 4
gpt4 key购买 nike

如何从 Spinner 中的 JSON 获取 id?

如果我在微调器中选择项目,我想要获取城市 ID

示例:/image/aTCJ2.jpg ,如果我选择“ACEH BARAT”,我将获得 ID“512”

public void displayCities(List<CityResponse.City> cities) {
for (CityResponse.City city : cities) {
Log.d(TAG, city.getNama());
spinnerItem.add(city.getNama());
adapter.notifyDataSetChanged();
}

}
private void setSpinner(Context context){
adapter = new ArrayAdapter<>(context, R.layout.spinner_item, spinnerItem);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainBinding.spinnerCity.setAdapter(adapter);
mainBinding.spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String citySelected = parent.getItemAtPosition(position).toString();
Toast.makeText(context, "City : " + citySelected, Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Not Selected", Toast.LENGTH_LONG).show();
}
});
}

最佳答案

您需要创建另一个数组列表来存储 id

 locationId.add(i, response.getData());

现在您需要在微调器中获取 Id

  spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
try {

selectedId = (String) locationId.get(position);


} catch (Exception e) {

}
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});

关于java - 如何在 Spinner 中从 JSON 获取所选项目 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56607600/

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