【问题标题】:Creating Dynamic RadioButtons from JSON Data从 JSON 数据创建动态单选按钮
【发布时间】:2018-07-05 14:37:18
【问题描述】:

我从 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;

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

【问题讨论】:

    标签: android radio-button radio-group jsonparser


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      相关资源
      最近更新 更多