【问题标题】:Save Radio button selection to String Array将单选按钮选择保存到字符串数组
【发布时间】:2016-06-07 06:48:07
【问题描述】:

我正在开发一个测验应用程序,其中有 20 个多项选择题。我必须将选中的单选按钮值存储到字符串数组,以便稍后在应用程序中使用用户选择的答案。下面是获取单选按钮文本的代码。现在如何将这 20 个选择保存到一个数组中?

if (rg.getCheckedRadioButtonId() != -1) {
                RadioButton uans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
                String ansText = uans.getText().toString();
}

【问题讨论】:

  • 只有一个屏幕包含20个问题或不同的屏幕用于不同的问题?
  • @ManishMenaria 这是一个屏幕,我正在使用字符串数组来处理问题和选项,用户必须单击下一步才能转到下一个问题
  • 活动保持不变?
  • @ManishMenaria 是的,活动保持不变

标签: android arrays string radio-button


【解决方案1】:

您可以将它们保存在字符串数组列表中 其中问题的索引也是数组中答案的索引

ArrayList<String> answersStringArray= new ArrayList<String>();

    if (rg.getCheckedRadioButtonId() != -1) {
        RadioButton uans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
        String ansText = uans.getText().toString();
        answersStringArray.add(ansText);
    }

【讨论】:

    【解决方案2】:

    您可以声明 HashMap 以逐个保存复选框值

     HashMap<String,String> hm=new HashMap<>();
    

    选中单选按钮时使用hm.put(question_number,checked_answer); 向HashMap 添加新值

    如果在检查后再次取消选中问题,则使用hm.remove(question_number);从哈希图中删除值

    你可以在完成测验后这样遍历HashMap

    for(String key :hm.keySet()){
         System.out.println(hm.get(key));
        }
    

    【讨论】:

      【解决方案3】:

      你能得到questText吗?

      尝试使用 HashMap

      HashMap<String,String> mMap = new HashMap<>();
      if (rg.getCheckedRadioButtonId() != -1) {
          RadioButton uans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
          String ansText = uans.getText().toString();
          mMap.put(quesText,ansText);
      }
      

      如果你只保存答案,你可以使用 ArrayList

      ArrayList<String> mArrayList = new ArrayList<>();
      if (rg.getCheckedRadioButtonId() != -1) {
      RadioButton uans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
      String ansText = uans.getText().toString();
      mArrayList.add(ansText);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-30
        • 2016-07-31
        • 1970-01-01
        • 2019-12-18
        • 1970-01-01
        • 1970-01-01
        • 2012-02-05
        • 2023-03-13
        相关资源
        最近更新 更多