【问题标题】:Data is not getting added in arraylist for radiogroup?数据没有被添加到radiogroup的arraylist中?
【发布时间】:2017-07-18 17:36:58
【问题描述】:

我想根据单选组的checkedId在ArrayList“arr”中添加数据。我有4个单选按钮“a0,a1,a2,a3”。所以如果我选择a1,数组列表应该加上rb2的值。在选择 a1 之后,如果我选择 a2,那么“arr”中的前一个值应该会更新(不会在第一个值之后添加)等等。任何帮助..

   rg.setOnCheckedChangeListener(new  RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {

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

            for (int i = 0; i <= mcq.size(); i++) {
                switch (checkedId) {
                    case R.id.a0:
                        // do operations specific to this selection

                        Toast.makeText(getApplication(),
                                rb1.getText(), Toast.LENGTH_SHORT).show();
                        break;

                    case R.id.a1:
                        // do operations specific to this selection

                        Toast.makeText(getApplication(),
                                rb2.getText(), Toast.LENGTH_SHORT).show();
                        break;

                    case R.id.a2:
                        // do operations specific to this selection

                        Toast.makeText(getApplication(),
                                rb3.getText(), Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.a3:
                        // do operations specific to this selection

                        Toast.makeText(getApplication(),
                                rb4.getText(), Toast.LENGTH_SHORT).show();
                        break;

                }
                arr.add(String.valueOf(checkedId));
                Log.e("", String.valueOf(arr));
            }


        }
    });

【问题讨论】:

    标签: android arraylist radio-button radio-group


    【解决方案1】:

    您可以使用https://developer.android.com/reference/android/util/SparseArray.html

    SparaseArray<Boolean> array = new SparseArray();
    array.put(checkedId, rb.isChecked());
    

    然后你可以像这样获取数组的所有选中元素:

    for(int i = 0; i< sparseArray.size(); i++) {
       int id = sparseArray.keyAt(i);
       Boolean isChecked = sparseArray.get(id);
       if(isChecked) {
           log("Identifier " + id + " is checked");
       }
    }
    

    【讨论】:

    • 我得到“无法解析符号”。我必须先定义它的大小。@AlexanderKulyakhtin
    猜你喜欢
    • 2017-10-08
    • 2018-07-30
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多