2013-07-17 2 views
4

Я сделал RadioGroup с переменным количеством кнопок radioButtons. Проблема в том, что многие радиокнопки могут быть проверены, это не один RadioButton проверено в RadioGroup (как я знаю) Где моя ошибка? Вот мой код:Inflating RadioGroup в Android-multiple radioButtons проверяется за один раз

View view = inflater.inflate(R.layout.questionnaire_check_question, null); 
RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup); 
    for (int k = 0; k < answerValues.size(); k++) { 
     View radioButtonView = inflater.inflate(R.layout.check_radio_button, null); 
     RadioButton radioButton = (RadioButton) radioButtonView 
          .findViewById(R.id.radio_button); 
     radioButton.setText(answerValues.get(k)); 
     radioGroup.addView(radioButtonView); 
    } 
questionBody.addView(view); 

questionnaire_check_question.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="5dp" 
    android:background="#A4A7A6" > 

    <RadioGroup 
     android:id="@+id/radioGroup" 
     android:scrollbars="horizontal" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 
    </RadioGroup> 

</LinearLayout> 

check_radio_button.xml

<?xml version="1.0" encoding="utf-8"?> 
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/radio_button" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:layout_weight="1" 
    android:layout_marginLeft="5dp" 
    android:button="@drawable/checkbox" 
> 

</RadioButton> 

вытяжке/checkbox.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android" > 

    <item android:drawable="@drawable/icon_checkbox_on" android:state_checked="true"/> 
    <item android:drawable="@drawable/icon_checkbox_off" android:state_checked="false"/> 

</selector> 

У радиогруппы есть странная функциональность. Если я проведу первую радиогруппу, а затем вторую, первая на непроверенной ... после этого, если я хочу снова выбрать первый, я не могу сделать это ... больше не проверяется. Может ли кто-нибудь мне помочь? Любая идея приветствуется! Спасибо заранее.

ответ

7

Я нашел решение: проблема в том, что все кнопки имеют одинаковый идентификатор. Поэтому я устанавливаю уникальный идентификатор для каждого radioButton.

-2

Я приводил пример, как это делается, затем вы соответствующим образом изменяете свой код. В вашем XML, чтобы добавить кнопки радио, вам нужно определить расположение, как показано ниже -

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <RadioGroup 
     android:id="@+id/radioSex" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" > 

     <RadioButton 
      android:id="@+id/radioMale" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/radio_male" 
      android:checked="true" /> 

     <RadioButton 
      android:id="@+id/radioFemale" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/radio_female" /> 

    </RadioGroup> 

    <Button 
     android:id="@+id/btnDisplay" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/btn_display" /> 

</LinearLayout> 

В вашем Java файл, выполните следующие действия: я) Объявить радио группу и радиокнопку, как показано ниже -

private RadioGroup radioSexGroup; 
    private RadioButton radioSexButton; 
    private Button btn; 

б) Зарегистрировать свой радиокнопку и RadioGroup с макетом XML, как ниже -

radioSexGroup = (RadioGroup) findViewById(R.id.radioSex); 
    btnDisplay = (Button) findViewById(R.id.btnDisplay); 

III) Добавить onclicklistner на кнопку, как показано ниже -

btn.setOnClickListner(this); 

IV) Реализовать интерфейс OnClickListner и Переопределение нереализованных методов интерфейса OnClickListner

v) В перекрытом методе OnClick, код следующий -

int selectedId = radioSexGroup.getCheckedRadioButtonId(); 

      // find the radiobutton by returned id 
       radioSexButton = (RadioButton) findViewById(selectedId); 

      Toast.makeText(MyAndroidAppActivity.this, 
       radioSexButton.getText(), Toast.LENGTH_SHORT).show(); 

И вот как это делается ..Надеюсь это поможет.

Смежные вопросы