首页 > 解决方案 > 从 JSON 数据创建动态单选按钮

问题描述

我从 api 获取数据,我想将小数组显示为单选按钮,因为用户应该只有一个选择。

这是我从网络获取数据的代码:

if (coachName != null && coachId != null) {
        nameTV.setText(coachName);
        fetchBatches(coachId);
        createGroups();
    }

fetchBatches(id),我在 json 响应方法中做到了这一点:

if (response != null) {
                        Log.d(TAG, "Batches Response:\t" + response.toString());
                        try {
                            JSONObject object = new JSONObject(response.toString());

                            String message = object.getString("message");

                            JSONArray array = object.getJSONArray("batch_details");
                            for (int m = 0; m < array.length(); m++) {

                                JSONObject jsonObject = array.getJSONObject(m);

                                name_batch = jsonObject.getString("batch_name");
                                id_batch = jsonObject.getString("batch_id");

                                batch = new BatchResponse();
                                batch.setBatchId(id_batch);
                                batch.setBatchName(name_batch);

                                list.add(batch);

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

它运行良好,创建单选按钮的方法:

radioButtons = new RadioButton[list.size()];
    for (int i = 0; i < list.size(); i++) {
        radioButtons[i] = new RadioButton(this);
        radioButtons[i].setGravity(Gravity.CENTER_HORIZONTAL);
        batchGroup.addView(radioButtons[i]);
        radioButtons[i].setText(list.get(i).getBatchName());
        radioButtons[i].setChecked(false);
    }

但屏幕上什么也没有显示。以下是用于每种方法的全局变量:

private RadioGroup batchGroup;
private BatchResponse batch;
private List<BatchResponse> list = new ArrayList<>();
private String name_batch, id_batch;
private RadioButton[] radioButtons;

我设置错了吗?我需要帮助解决这个问题。谢谢。

标签: androidradio-buttonradio-groupjsonparser

解决方案


尝试在 fetchBatches(coachId) 方法中的 for 循环之后调用 createGroups() 方法。


推荐阅读