2016-05-12 88 views
0

我想根據radio組的checkedId在ArrayList「arr」中添加數據。我有4個單選按鈕「a0,a1,a2,a3」。所以如果我選擇a1,數組列表應該添加rb2的值。並選擇A1後,如果我選擇A2然後在「ARR」以前的值應該得到更新(沒有得到的第一個後加入)等on.Any幫助..數據沒有被添加到radiolroup的數組列表中?

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)); 
      } 


     } 
    }); 

回答

0

您可以使用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"); 
    } 
} 
+0

我得到「無法解析符號」。做我必須首先確定其大小@ AlexanderKulyakhtin –