【问题标题】:Getting CheckBox id and text when dynamically created using for loop使用 for 循环动态创建时获取 CheckBox id 和文本
【发布时间】:2017-04-16 22:33:07
【问题描述】:

我有一个按钮、问题和多个使用 for 循环动态创建的复选框,看起来像这样

这就是我获取所有数据以及创建问题和复选框的方式

try {
JSONArray jsonArray = response.getJSONArray("values");

for (int i = 0; i < jsonArray.length(); i++) {
 JSONObject category = jsonArray.getJSONObject(i);
 categoryTxt = category.getString("category");
 Log.v("category", categoryTxt);

 //create Question
 TextView title = new TextView(FactorsActivity.this);
 title.setTextSize(20);
 title.setId(i);
 title.setText(categoryTxt);
 title.setTextColor(Color.BLUE);
 mLinearLayout.addView(title);

 JSONArray factors = category.getJSONArray("factors");

 Log.v("size factors", String.valueOf(factors.length()));
 nameArray = new String[factors.length()];
 for(int j = 0; j < factors.length(); j++)
 {
  JSONObject factorsObj = factors.getJSONObject(j);
  id = factorsObj.getString("id");
  //Log.v("id", id);
  name = factorsObj.getString("name");
  // Log.v("name", name);

  nameArray[j] = name;

  checkBox = new CheckBox(FactorsActivity.this);
  checkBox.setId(Integer.parseInt(id));
  checkBox.setText(nameArray[j]);
  mLinearLayout.addView(checkBox);

 }
}

现在我的主要目标是,假设我选中了每天框,然后单击提交。当我点击提交时,我想要所有选中的复选框信息,例如问题、它的 ID 和它的文本。这里的信息应该是

  1. 问题:头痛复发
  2. 复选框 ID:数字
  3. 复选框文本:每天 非常感谢。

【问题讨论】:

    标签: android android-studio checkbox


    【解决方案1】:

    就像使用 name 一样,将动态创建的 CheckBox 项目的引用存储在这样的数组中:

    checkboxArray[j] = checkBox;
    

    然后遍历该数组以获取CheckBox ID 及其文本。

    【讨论】:

    • 点击提交按钮时如何存储?
    • 据我了解,您只想存储问题、复选框 ID 和复选框文本。您不需要存储对复选框的引用,因为该引用会随着应用启动而改变。
    • 如果用户单击提交按钮,我想存储。因为我是动态创建的,所以我不知道如何解决它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2020-09-28
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2016-03-09
    相关资源
    最近更新 更多