簡體   English   中英

如何在不帶ID的RadioGroup中默認檢查RadioButton?

[英]How to default check RadioButton in RadioGroup without Id?

因此,我在RadioGroup中有一個RadioButton,應檢查該方法,而不要使用Id。

這是我的XML代碼:

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

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RadioButton 1" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RadioButton 2" />
</RadioGroup>

在這里,我檢查選定的RadioButton:

RadioGroup radioGroup = findViewById(R.id.radioGroup);
int radioButtonId = radioGroup.getCheckedRadioButtonId();

switch (radioButtonId) {
    case 1:
        doSomething();
        break;
    case 2:
        doSomething();
        break;
}

我嘗試過這個:

1)向RadioGroup添加了屬性android:android:checkedButton。

<RadioGroup
    android:id="@+id/radioGroup"
    android:checkedButton="@id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RadioButton 1" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RadioButton 2" />
</RadioGroup>

由於radioButtonId不是索引,而是ID,所以未執行doSometheing()。

2)然后,我向RadioButton添加了一個屬性android:checked為“ true”。

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

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="RadioButton 1" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RadioButton 2" />
</RadioGroup>

doSometheing()已執行,但是現在可以同時檢查兩個RadioButton。 不能取消選中第一個RadioButton。 radioButtonId保持不變== 1。

希望您能告訴我正確的方法。

謝謝。 祝你今天愉快。

使用findviewbyid:

radiobutton1 =(RadioButton)findViewById(R.id.radiobutton1);
radiobutton1.setChecked(true);

您可以按如下方式獲取checked RadioButton索引:

int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);

switch (idx) {
    case 1:
        doSomething();
        break;
    case 2:
        doSomething();
        break;
}

注意:不要忘記為radio buttons分配id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM