2017-03-02 62 views
0

在我的應用程序中,我將根據需求動態添加RadioButton。 下面是代碼:動態添加時如何檢查RadioButton?

RadioGroup rg = new RadioGroup(StartExamActivity.this); 
      View v = new View(StartExamActivity.this); 
      v.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2)); 
      v.setBackgroundColor(Color.parseColor("#3593D4")); 
      rg.setLayoutParams(new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); 
      rg.setOrientation(LinearLayout.VERTICAL); 
      for (int i = 0; i < list.size(); i++) { 
       rdbtn[i] = new RadioButton(StartExamActivity.this); 
       rdbtn[i].setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT, 1f)); 
       rdbtn[i].setId(i); 
       rdbtn[i].setText(list.get(i)); 
       final String value = rdbtn[i].getText().toString(); 

       rdbtn[i].setOnClickListener(new View.OnClickListener() { 
        public void onClick(View v) { 
         if (value.equalsIgnoreCase(answer)) { 
          marks = marks + 2; 
         } 
        } 
       }); 
       rg.addView(rdbtn[i]); 
      } 
      questionContainer.addView(rg); 

現在,我想即使單選按鈕會被多次檢出2個唯一增加的標記值。爲此,我想知道是否選中了RadioButton。 如何做到這一點??

請幫忙!!

+0

http://stackoverflow.com/questions/11050074/how-to-check-if-radiobutton-是檢查 –

+0

請參閱此鏈接(http://stackoverflow.com/questions/22855276/cant-get-the-values-from-dynamically-added-check-box)和[link2](http:// stackoverflow.com/questions/12213545/check-the-state-of-checkboxes-which-were-added-dynamically)希望它能爲你工作 –

回答

1

簡單的事情,

你爲什麼不使用OnClickListener代替onCheckedChanged>

rdbtn[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
        @Override 
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { 
         if(isChecked) { 
          // Write your logic here... 
         } 
        });