如何在Android中获取RadioGroup的选定索引

发布于 2024-11-16 18:44:20 字数 1094 浏览 2 评论 0原文

有没有一种简单的方法可以获取 Android 中 RadioGroup 的选定索引,或者我是否必须使用 OnCheckedChangeListener 来侦听更改并拥有保存最后选定索引的内容?

示例 xml:

<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <RadioButton android:id="@+id/radio1" android:text="option 1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio2" android:text="option 2" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio3" android:text="option 3" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio4" android:text="option 4" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio5" android:text="option 5" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RadioGroup>

如果用户选择选项 3,我想获取索引 2。

Is there an easy way to get the selected index of a RadioGroup in Android or do I have to use OnCheckedChangeListener to listen for changes and have something that holds the last index selected?

example xml:

<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <RadioButton android:id="@+id/radio1" android:text="option 1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio2" android:text="option 2" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio3" android:text="option 3" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio4" android:text="option 4" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio5" android:text="option 5" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RadioGroup>

if a user selects option 3 I want to get the index, 2.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

就此别过 2024-11-23 18:44:20

您应该能够执行以下操作:

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

如果 RadioGroup 包含其他视图(例如 TextView),则 indexOfChild() 方法将返回错误的索引。

要获取 RadioGroup 上选定的 RadioButton 文本:

 RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
 String selectedtext = r.getText().toString();

You should be able to do something like this:

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

If the RadioGroup contains other Views (like a TextView) then the indexOfChild() method will return wrong index.

To get the selected RadioButton text on the RadioGroup:

 RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
 String selectedtext = r.getText().toString();
迷爱 2024-11-23 18:44:20

这应该有效,

int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));

This should work,

int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));
内心旳酸楚 2024-11-23 18:44:20

您可以引用单选按钮组并使用 getCheckedRadioButtonId () 来获取选中的单选按钮 ID。看一下这里

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);

然后当你需要时获取所选的收音机选项。

int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (checkedRadioButtonId == -1) {
    // No item selected
}
else{
    if (checkedRadioButtonId == R.id.radio_button1) {
        // Do something with the button
    }
}

You could have a reference to the radio group and use getCheckedRadioButtonId () to get the checked radio button id. Take a look here

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);

Then when you need to get the selected radio option.

int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (checkedRadioButtonId == -1) {
    // No item selected
}
else{
    if (checkedRadioButtonId == R.id.radio_button1) {
        // Do something with the button
    }
}
夏雨凉 2024-11-23 18:44:20

试试这个

        RadioGroup  group= (RadioGroup) getView().findViewById(R.id.radioGroup);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                View radioButton = radioGroup.findViewById(i);
                int index = radioGroup.indexOfChild(radioButton);
            }
        });

try this

        RadioGroup  group= (RadioGroup) getView().findViewById(R.id.radioGroup);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                View radioButton = radioGroup.findViewById(i);
                int index = radioGroup.indexOfChild(radioButton);
            }
        });
够钟 2024-11-23 18:44:20

您可以使用 OnCheckedChangeListener 或使用 getCheckedRadioButtonId()

You can either use OnCheckedChangeListener or can use getCheckedRadioButtonId()

人心善变 2024-11-23 18:44:20

您可以使用:

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());

You can use:

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
诺曦 2024-11-23 18:44:20

//用于获取所选项目的id

int selectedID = myRadioGroup.getCheckedRadioButtonId();

//获取所选项目的视图

View selectedView = (View)findViewById( selectedID);

//use to get the id of selected item

int selectedID = myRadioGroup.getCheckedRadioButtonId();

//get the view of the selected item

View selectedView = (View)findViewById( selectedID);
隔纱相望 2024-11-23 18:44:20

它以这种方式对我来说非常有效:

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
    int radioButtonID = radioGroup.getCheckedRadioButtonId();
    RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonID);
    String selectedtext = (String) radioButton.getText();

It worked perfectly for me in this way:

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
    int radioButtonID = radioGroup.getCheckedRadioButtonId();
    RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonID);
    String selectedtext = (String) radioButton.getText();
青衫儰鉨ミ守葔 2024-11-23 18:44:20

科特林:

val selectedIndex = radioButtonGroup?.indexOfChild(
  radioButtonGroup?.findViewById(
    radioButtonGroup.getCheckedRadioButtonId())
)

Kotlin:

val selectedIndex = radioButtonGroup?.indexOfChild(
  radioButtonGroup?.findViewById(
    radioButtonGroup.getCheckedRadioButtonId())
)
2024-11-23 18:44:20

您所需要的只是首先为您的 RadioButton 设置值,例如:

RadioButton radioButton = (RadioButton)findViewById(R.id.radioButton);      
radioButton.setId(1);        //some int value

然后每当选择这个特定的 radioButton 时,您都可以通过您给它的 Id 来拉取它的值

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);                     
int whichIndex = radioGroup.getCheckedRadioButtonId(); //of course the radioButton
                                                       //should be inside the "radioGroup"
                                                       //in the XML

,干杯!

All you need is to set values first to your RadioButton, for example:

RadioButton radioButton = (RadioButton)findViewById(R.id.radioButton);      
radioButton.setId(1);        //some int value

and then whenever this spacific radioButton will be chosen you can pull its value by the Id you gave it with

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);                     
int whichIndex = radioGroup.getCheckedRadioButtonId(); //of course the radioButton
                                                       //should be inside the "radioGroup"
                                                       //in the XML

Cheers!

何处潇湘 2024-11-23 18:44:20
radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);

  btnDisplay=(Button)findViewById(R.id.button);

  btnDisplay.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        int selectedId=radioSexGroup.getCheckedRadioButtonId();
        radioSexButton=(RadioButton)findViewById(selectedId);
        Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
     }
  });
radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);

  btnDisplay=(Button)findViewById(R.id.button);

  btnDisplay.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        int selectedId=radioSexGroup.getCheckedRadioButtonId();
        radioSexButton=(RadioButton)findViewById(selectedId);
        Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
     }
  });
妥活 2024-11-23 18:44:20

聚会迟到了,但这里是 @Tarek360 的 Kotlin 答案的简化,它适合可能包含非 RadioButtons 的 RadioGroup

    val RadioGroup.checkedIndex: Int
        get() = children
            .filter { it is RadioButton }
            .indexOfFirst { it.id == checkedRadioButtonId }

如果您是 RadioFroup 肯定只有 < code>RadioButtons 那么这可以很简单:

    private val RadioGroup.checkedIndex = 
        children.indexOfFirst { it.id == checkedRadioButtonId }

那么您就没有 findViewById 的开销。

Late to the party, but here is a simplification of @Tarek360's Kotlin answer that caters for RadioGroups that might contain non-RadioButtons:

    val RadioGroup.checkedIndex: Int
        get() = children
            .filter { it is RadioButton }
            .indexOfFirst { it.id == checkedRadioButtonId }

If you're RadioFroup definitely only has RadioButtons then this can be a simple as:

    private val RadioGroup.checkedIndex = 
        children.indexOfFirst { it.id == checkedRadioButtonId }

Then you don't have the overhead of findViewById.

爱情眠于流年 2024-11-23 18:44:20
 int index_selected = radio_grp.indexOfChild(radio_grp
                .findViewById(radio_grp.getCheckedRadioButtonId()));
 int index_selected = radio_grp.indexOfChild(radio_grp
                .findViewById(radio_grp.getCheckedRadioButtonId()));
我只土不豪 2024-11-23 18:44:20

只需使用这个:

    int index = 2;
    boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();

just use this:

    int index = 2;
    boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();
意中人 2024-11-23 18:44:20

这是一个 Kotlin 扩展,用于获取正确的位置,即使您的组包含 TextView 或任何非 RadioButton。

fun RadioGroup.getCheckedRadioButtonPosition(): Int {
    val radioButtonId = checkedRadioButtonId
    return children.filter { it is RadioButton }
        .mapIndexed { index: Int, view: View ->
            index to view
        }.firstOrNull {
            it.second.id == radioButtonId
        }?.first ?: -1
}

Here is a Kotlin extension to get the correct position even if your group contains a TextView or any non-RadioButton.

fun RadioGroup.getCheckedRadioButtonPosition(): Int {
    val radioButtonId = checkedRadioButtonId
    return children.filter { it is RadioButton }
        .mapIndexed { index: Int, view: View ->
            index to view
        }.firstOrNull {
            it.second.id == radioButtonId
        }?.first ?: -1
}
伴随着你 2024-11-23 18:44:20

你可以

findViewById

从广播组做。

这是示例:

((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);

you can do

findViewById

from the radio group .

Here it is sample :

((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);
无人接听 2024-11-23 18:44:20

您可以简单地

- 在 onCreate 方法中声明单选组和单选按钮

private RadioGroup GrupName;
private RadioButton NameButton;

- 在 onCreate 方法中

GrupName = (RadioGroup) findViewById(R.id.radioGroupid);

设置视图 id - 获取使用选择的单选按钮

int id = GroupName.getCheckedRadioButtonId();

id - 使用 id 来匹配按钮选择的视图

NameButton = (RadioButton) findViewById(id);

- 最后获取单选按钮的值

String valueExpected = NameButton.getText().toString();

--- PS:如果你想要一个 INT 值,那么你可以转换它

int valueExpectedIn = Integer.parseInt(valueExpected);

You can simply

-declare the radio group and a radio button out of onCreate method

private RadioGroup GrupName;
private RadioButton NameButton;

-set the view id in the onCreate method

GrupName = (RadioGroup) findViewById(R.id.radioGroupid);

-take the radiobutton id selected using

int id = GroupName.getCheckedRadioButtonId();

-use the id to match the buttonselected view

NameButton = (RadioButton) findViewById(id);

-finally get the value of the radio button

String valueExpected = NameButton.getText().toString();

--- PS: IF YOU WANT AN INT VALUE, THEN YOU CAN CAST IT

int valueExpectedIn = Integer.parseInt(valueExpected);
孤云独去闲 2024-11-23 18:44:20

您已经为每个单选按钮分配了一个 ID。使用 case 块,您可以手动检测选定的单选按钮,或者使用 OnCheckedChangeListener 也可以检测到它。

xml:

    <RadioGroup
        android:id="@+id/rd_group_pick_reason"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/ti_titel"
        android:orientation="horizontal"
        android:paddingHorizontal="16dp"
        >
        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/rd_not_deliverable"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/txt_not_deliverable"
            android:checked="true"
            />

        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/rd_after_pack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/txt_after_pack"
            />
    </RadioGroup>

java:

final RadioGroup radioGroup = dialogView.findViewById(R.id.rd_group_pick_reason);    
switch (radioGroup.getCheckedRadioButtonId()) {
    case R.id.rd_not_deliverable:
        // TODO
    break;
    case R.id.rd_after_pack:
        // TODO
    break;
}

radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
    switch (group.getCheckedRadioButtonId()) {
        case R.id.rd_not_deliverable:
            System.out.println("not deliverable");
            break;
        case R.id.rd_after_pack:
            System.out.println("after pack");
            break;
    }

You have already assigned an id for each radio button. With a case block you can detect manually the selected radio button or with OnCheckedChangeListener you get it too.

xml:

    <RadioGroup
        android:id="@+id/rd_group_pick_reason"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/ti_titel"
        android:orientation="horizontal"
        android:paddingHorizontal="16dp"
        >
        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/rd_not_deliverable"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/txt_not_deliverable"
            android:checked="true"
            />

        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/rd_after_pack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/txt_after_pack"
            />
    </RadioGroup>

java:

final RadioGroup radioGroup = dialogView.findViewById(R.id.rd_group_pick_reason);    
switch (radioGroup.getCheckedRadioButtonId()) {
    case R.id.rd_not_deliverable:
        // TODO
    break;
    case R.id.rd_after_pack:
        // TODO
    break;
}

or

radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
    switch (group.getCheckedRadioButtonId()) {
        case R.id.rd_not_deliverable:
            System.out.println("not deliverable");
            break;
        case R.id.rd_after_pack:
            System.out.println("after pack");
            break;
    }
不如归去 2024-11-23 18:44:20
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();
            // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
        }
    });
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();
            // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
        }
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文