首页 > 解决方案 > 如何在 Web api 响应中添加动态复选框?

问题描述

这是我的代码,我在多个时间槽中得到响应我想根据时间响应创建多个复选框这是我的代码:

  @Override
        public void onResponse(String response) {
            pd.dismiss();
            Log.e("@@TimeApi", response);
            try {

                JSONObject obj = new JSONObject(response);
                JSONObject objData = obj.getJSONObject("data");
                JSONArray jsonArray = objData.getJSONArray("time");

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                if (!obj.getBoolean("error")) {

                    for (int i=0; i<jsonArray.length(); i++){

                        String time = jsonArray.getString(i);
                        Log.e("@@Time", time);
                        final List<String> timeList = Arrays.asList(time);


                    }
                } else {
                    Toast.makeText(getActivity(), obj.getString("message"), Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

在 for 循环中,我现在有时间了,我需要用复选框将时间放在对话框中

在日志中,我收到这样的回复,可能有多个

标签: androidjsoncheckboxdialog

解决方案


在 AlertDialog 中,您需要在 setMultipleChoiceItems 中设置列​​表,检查以下代码

@Override
        public void onResponse(String response) {
            pd.dismiss();
            Log.e("@@TimeApi", response);
            try {

                JSONObject obj = new JSONObject(response);
                JSONObject objData = obj.getJSONObject("data");
                JSONArray jsonArray = objData.getJSONArray("time");

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                if (!obj.getBoolean("error")) {
                    String[] timeList = new String[jsonArray.length()];
                    boolean[] checkedItems = new boolean[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {

                        String time = jsonArray.getString(i);
                        Log.e("@@Time", time);
                        timeList[i] = time;
                        checkedItems[i] = false;
                    }

                    builder.setMultiChoiceItems(timeList, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            Log.i("@@Time", "position" + which + " state " + isChecked);
                        }
                    });
                } else {
                    Toast.makeText(getActivity(), obj.getString("message"), Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


推荐阅读