Android - 如何在微调器

时间:2018-04-04 12:33:25

标签: android rest retrofit2

我的休息响应如下,我需要将输出填充到微调器。我已成功地将“名称”传递给微调器并且它的工作原理。但我还需要获取“id”,以便我可以使用“id”查询另一个休息请求。例如,我获得省份ID,然后我使用省号来获取城市列表。

{
"code": 1000,
"message": "OK",
"data": [
    {
        "id": "3579010",
        "name": "Batu"
    },
    {
        "id": "3579020",
        "name": "Junrejo"
    },
    {
        "id": "3579030",
        "name": "Bumiaji"
    }
  ]
}

下面是android代码

public void initProvinceSpinner() {

    Call<GetProvinceResponse> call = apiService.getProvinceResponse();
    call.enqueue(new Callback<GetProvinceResponse>() {

        @Override
        public void onResponse(Call<GetProvinceResponse> call, Response<GetProvinceResponse> response) {

            ArrayList<GetProvinceResponseData> provinceResponseData = response.body().getData();
            List<String> listProvinceNameSpinner = new ArrayList<String>();
            //List<String> listProvinceIdSpinner = new ArrayList<String>();

            for(int i = 0; i<provinceResponseData.size();i++){
                listProvinceNameSpinner.add(provinceResponseData.get(i).getName());
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, listProvinceNameSpinner);
            provinceToko.setAdapter(adapter);

        }

        @Override
        public void onFailure(Call<GetProvinceResponse> call, Throwable t) {

        }
    });
}

1 个答案:

答案 0 :(得分:1)

试试这个

获取ID:

provinceResponseData.get(spinner.getSelectedItemPosition()).getId();

添加微调器侦听器:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        // call the service and pass the parameter
        serviceCall(provinceResponseData.get(spinner.getSelectedItemPosition()).getId());
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        // your code here
    }

});