Как я могу добавить переключатели в группу переключателей, которую я создал программно?

Я совершенно новичок в Android

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

main_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".Main"
    android:orientation="vertical"
    android:id="@+id/mainLayout">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton1" />
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton2" />
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton3" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton4" />
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton5" />

        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton6" />
    </LinearLayout>
</LinearLayout>

Main.java

public class Main extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        RadioButton rb1 = (RadioButton) findViewById(R.id.radioButton1);
        RadioButton rb2 = (RadioButton) findViewById(R.id.radioButton2);
        RadioButton rb3 = (RadioButton) findViewById(R.id.radioButton3);
        RadioButton rb4 = (RadioButton) findViewById(R.id.radioButton4);
        RadioButton rb5 = (RadioButton) findViewById(R.id.radioButton5);
        RadioButton rb6 = (RadioButton) findViewById(R.id.radioButton6);

        RadioGroup rg = new RadioGroup(this);
        rg.addView(rb1);
        rg.addView(rb2);
        rg.addView(rb3);
        rg.addView(rb4);
        rg.addView(rb5);
        rg.addView(rb6);

    }

}

на самом деле я пытаюсь создать радиогруппу с 3 столбцами и 2 строками, но, как я ни пытался, это не работает, когда я делаю это так:

main_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".Main"
    android:orientation="vertical"
    android:id="@+id/mainLayout">
  <RadioGroup
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton1" />
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton2" />
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton3" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton4" />
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton5" />
        <RadioButton
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="New RadioButton"
            android:id="@+id/radioButton6" />
    </LinearLayout>
 </RadioGroup>
</LinearLayout>

последнее решение, которое я получил, - это создать радиогруппу в Main.java программно, но это делает ошибку в методе rg.addView()


person ShahinSorkh    schedule 12.08.2015    source источник
comment
RadioGroup rg = new RadioGroup(this);. Нет, вы должны определить пустую RadioGroup в файле xml. Затем во время выполнения создайте RadioButtons и добавьте их в RadioGroup.   -  person greenapps    schedule 12.08.2015
comment
Вот и все - stackoverflow.com/questions/6646442/   -  person Andrew Fielden    schedule 12.08.2015


Ответы (2)


Попробуйте создать RadioGroup в xml и получите ссылку на нее в java, а затем используйте ссылку, чтобы делать свои вещи. Или вы можете добавить RadioGroup в свой макет, если хотите сохранить java RadioGroup.

person LukaxH    schedule 12.08.2015
comment
нет, это не работает, потому что вы не можете добавить к нему RadioButtons. вы сталкиваетесь с ошибкой, потому что пытаетесь добавить представления в родителя, внутри которых они уже есть! (извините за мой ломаный английский) - person ShahinSorkh; 17.08.2015

Я нашел свое решение!

Я создал новый класс RadioGroup, в котором я могу поместить свои RadioButtons в группу, не нарушая моего макета main.xml!

вот класс, который я только что создал:

import android.view.View;
import android.widget.RadioButton;

/**
 * <p>
 *     CREATED:<br />&nbsp;&nbsp;&nbsp;&nbsp;
 *          15 Aug 2015
 * </p>
 * <p>
 *     This class is created to make a RadioGroup
 *     with no limitation of designing and layouting.
 *  <br />
 *  <strong>
 *      The first method you have to call is
 *      <em>createRadioGroup ()</em> to
 *      initialize your RadioGroup.
 *  </strong>
 *  <br />
 *     Feel free to browse in the class
 *     and making change in it as you need.
 * </p>
 * @author ShahinSorkh
 * @version 1
 */
public class RadioGroup2 {

// Global variables
private RadioButton rb [];
private int firstCheckedItemId;
public static int countRadioButtons;

/**
 * <p>
 *     will initialize your RadioGroup
 * </p>
 * <p>
 *     <strong>an example:</strong>
 *     <p>
 *         RadioGroup2 rg = new RadioGroup2;<br />
 *         RadioButton rb [] = new RadioButton[3];<br />
 *         rb[0] = (RadioButton)findViewById(R.id.radio1);<br />
 *         rb[1] = (RadioButton)findViewById(R.id.radio2);<br />
 *         rb[2] = (RadioButton)findViewById(R.id.radio3);<br />
 *         rg.createRadioGroup(rb);
 *     </p>
 * </p>
 * @param radioButtons an Array of RadioButtons
 */
public void createRadioGroup(RadioButton [] radioButtons){
    rb = radioButtons;
    firstCheckedItemId = getCheckedItemId();
    countRadioButtons = rb.length;
    onCheck();
}

private void onCheck(){
    for (RadioButton aRb : rb) {
        aRb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View radio) {
                final RadioButton myRb = (RadioButton) radio;
                for (RadioButton aRb : rb) {
                    if (aRb.getId() == myRb.getId()) {
                        aRb.setChecked(true);
                    } else aRb.setChecked(false);
                }
            }
        });
    }
}

/**
 * will count RadioButtons in your RadioGroup
 * @return the count of RadioButtons in RadioGroup
 */
public int getRadioButtonsCount(){
    return countRadioButtons;
}

/**
 * <p>
 *     will return the checked item <strong>ID</strong>
 *     <em>you can use in findViewById() for example</em>
 * </p>
 * <p>
 *     will return <em>-1</em> if no RadioButton has checked<br />
 *     better to check if any button has checked
 * </p>
 * @return int checkedRadioButtonId
 */
public int getCheckedItemId (){
    int id = -1;
    for (RadioButton aRb : rb) {
        if(aRb.isChecked())
            id = aRb.getId();
    }
    return id;
}

/**
 * <p>
 *     will return the checked <strong>RadioButton</strong>
 * </p>
 * <p>
 *     will return <em>null</em> if no RadioButton has checked<br />
 *     better to check if any button has checked
 * </p>
 * @return checked RadioButton directly
 */
public RadioButton getCheckedItem (){
    RadioButton RB = null;
    for (RadioButton aRb : rb) {
        if(aRb.isChecked())
            RB = aRb;
    }
    return RB;
}

/**
 * will reset all RadioButtons checked state
 * to default, all RadioButtons will unCheck
 * and the firstChecked RadioButton will check
 * at end
 */
public void resetButtons(){
    RadioButton iRb = getCheckedItem();
    if(iRb != null)
        iRb.setChecked(false);
    if(firstCheckedItemId != -1)
        getChildById(firstCheckedItemId).setChecked(true);
}

private RadioButton getChildById(int id){
    RadioButton iRb = null;
    for (RadioButton aRb : rb ) {
        if(aRb.getId() == id) {
            iRb = aRb;
            break;
        }
    }
    return iRb;
}

/**
 * <p>
 *     will return <strong>RadioButton</strong> at given index in the Array
 * </p>
 * @param position index of RadioButton in Array
 * @return RadioButton[i]
 */
public RadioButton getChildAt (int position){
    return rb[position];
}
}

и создайте мою RadioGroup следующим образом:

RadioGroup2 rg = new RadioGroup2 ();
RadioButton [] rb = new RadioButton [3]();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

rb[0] = (RadioButton) findViewById(R.id.rb1);
rb[1] = (RadioButton) findViewById(R.id.rb2);
rb[2] = (RadioButton) findViewById(R.id.rb3);

rg.createRadioGroup(rb);
...
}

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

спасибо всем, кто уделил этому время

person ShahinSorkh    schedule 17.08.2015