Android: RadioGroup - 如何配置事件监听器

63

据我理解,为了确定复选框是否被“点击”,并查找它是否被选中,可以使用以下代码:

cb=(CheckBox)findViewById(R.id.chkBox1);
        cb.setOnCheckedChangeListener(this);

public void onCheckedChanged(CompoundButton buttonView, 
    boolean isChecked) { 
        if (isChecked) { 
            cb.setText("This checkbox is: checked"); 
        } 
        else { 
            cb.setText("This checkbox is: unchecked"); 
        } 
    }

但是,我无法理解如何对单选组进行类似的操作。

这是我的RadioGroup的XML:

<RadioGroup android:id="@+id/radioGroup1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radio1" android:checked="true" 
    android:text="RadioButton1">
    </RadioButton>
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radio2" android:text="RadioButton2" android:checked="true">
    </RadioButton>
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radio3" android:text="RadioButton3">
    </RadioButton>
</RadioGroup>

问题:我需要设置另一个监听器吗,或者已经存在的监听器也会“注册”这个组?此外,监听器应该在RadioGroup还是RadioButton上设置?

6个回答

140

这是获取选中单选按钮的方法:

// This will get the radiogroup
RadioGroup rGroup = (RadioGroup)findViewById(r.id.radioGroup1);
// This will get the radiobutton in the radiogroup that is checked
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(rGroup.getCheckedRadioButtonId());

使用监听器时,您需要执行以下操作:

// This overrides the radiogroup onCheckListener
rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
    public void onCheckedChanged(RadioGroup group, int checkedId)
    {
        // This will get the radiobutton that has changed in its check state
        RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
        // This puts the value (true/false) into the variable
        boolean isChecked = checkedRadioButton.isChecked();
        // If the radiobutton that has changed in check state is now checked...
        if (isChecked)
        {
            // Changes the textview's text to "Checked: example radiobutton text"
            tv.setText("Checked:" + checkedRadioButton.getText());
        }
    }
});

本地变量rgroup可能尚未初始化。 - Ryan
4
我写第一行只是为了告诉你rGroup是什么。要获取rGroup,你需要写这句话:RadioGroup rGroup = (RadioGroup)findViewById(R.id.radioGroup1); - A. Abiri
我不明白,它告诉我radiogroup被选中了...但没有告诉我哪个单选按钮被选中了。我错过了什么吗? - Ryan
1
请再看一下我的答案。我已经编辑过了,并为每一行添加了注释,这样你就知道我在做什么了。此外,所检查的 id 不是单选按钮的名称,而是单选按钮的唯一标识符。 - A. Abiri
1
那个完美地运行了,同时也教会了我后台的所有“连线”,非常感谢! - Ryan
我以前从未真正理解这是如何工作的,但是您的示例代码和注释终于让我恍然大悟。 - sXe

22

它应该像这样。

RadioGroup rb = (RadioGroup) findViewById(R.id.radioGroup1);
rb.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {

            }
        }

    });

根据checkedId,您将知道单选按钮中哪个已被点击,然后使用上面的代码来确定其是否被选中或未选中。 这是一道作业题。 ;)


3
你的代码运行起来了,但我去掉了switch并加入了这个:tv.setText("blah:"+checkedId); 但是它给我返回了一些奇怪的数字,checkedID :( - Ryan
CheckedId是单选按钮组中被点击的按钮的id。您需要使用findViewbyId来理解它。 - PravinCG
我本以为这会起作用,但实际上并没有。当我更改三个按钮控件中的选定单选按钮时,我会收到三个通知,表示已更改检查状态。似乎每个按钮都有一个通知。但是在第一次通知中,checkedId的按钮对于Checked属性的值为false。Abiri的解决方案对我有效。 - Frank Schwieterman

19

使用 Switch 更好:

radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      public void onCheckedChanged(RadioGroup arg0, int id) {
        switch (id) {
        case -1:
          Log.v(TAG, "Choices cleared!");
          break;
        case R.id.chRBtn:
          Log.v(TAG, "Chose Chicken");
          break;
        case R.id.fishRBtn:
          Log.v(TAG, "Chose Fish");
          break;
        case R.id.stkRBtn:
          Log.v(TAG, "Chose Steak");
          break;
        default:
          Log.v(TAG, "Huh?");
          break;
        }
      }
    });

1
抛出以下警告:在Android Gradle插件版本5.0中,资源ID将是非最终的,请避免在switch case语句中使用它们。 - Luís Henriques

7
//Within the Activity that hosts this layout, the following method handles the click event for both radio buttons:

public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();

// Check which radio button was clicked
switch(view.getId()) {
    case R.id.radio_pirates:
        if (checked)
            // Pirates are the best
        break;
    case R.id.radio_ninjas:                       
        if (checked)
            // Ninjas rule
        break;
}
}

0
如果您想查看单选按钮组中哪个单选按钮被选中,请使用以下代码:
//1. declare the radio group and the radio Button in the java file.
RadioGroup radiobtn;
RadioButton radio;
Button btnClick;
 //the radio is the element of the radiogroup which will assigned when we select the radio button
 //Button to trigger the toast to show which radio button is selected of the radio group


//2. now define them in the java file
radiobtn = findViewById(R.id.radiobtn);
btnClick = findViewById(R.id.btnClick);
 //we are instructing it to find the elements in the XML file using the id


//3. Now Create an on Click listener for the button
btnClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int selectedId = radiobtn.getCheckedRadioButtonId();
             //we are defining the selectId and then we are fetching the id of the checked radio button using the function getCheckedRadioButton()
            radio = findViewById(selectedId);
             //now the radioButton object we have defined will come into play, we will assign the radio to the radio button of the fetched id of the radio group
            Toast.makeText(MainActivity.this,radio.getText(),Toast.LENGTH_SHORT).show();
             //we are using toast to display the selected id of the radio button
             //radio.getText() will fetch the id of the radio Button of the radio group
        }
    });

0

我的MainActivity.java

package com.example.endsempracmad;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
String selection;

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

    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle("Home Activity");

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




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

    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Create an intent to start the new activity
            Intent intent = new 
 Intent(MainActivity.this,SecondActivity.class);
            int selectedId = radioGroup.getCheckedRadioButtonId();
            if(selectedId != -1){
                RadioButton selectedRadioButton = findViewById(selectedId);
                selection = selectedRadioButton.getText().toString();


            }
            intent.putExtra("selection", selection);
            startActivity(intent);

            // Start the new activity
            startActivity(intent);
        }
    });

    //Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout             
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

 <Button
    android:id="@+id/button"
    android:layout_width="267dp"
    android:layout_height="123dp"
    android:layout_marginStart="45dp"
    android:layout_marginTop="450dp"
    android:layout_marginEnd="99dp"
    android:layout_marginBottom="158dp"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

 <RadioGroup
    android:id="@+id/my_radio_group"
    android:layout_width="166dp"
    android:layout_height="248dp"
    android:layout_marginStart="34dp"
    android:layout_marginTop="129dp"
    android:layout_marginEnd="211dp"
    android:layout_marginBottom="354dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="69dp"
        android:background="@drawable/messi"
        android:text="Radio button 1" />

    <RadioButton
        android:layout_width="120dp"
        android:layout_height="81dp"
        android:background="@drawable/messi"
        android:text="Radio button 2" />

    <RadioButton
        android:layout_width="123dp"
        android:layout_height="84dp"
        android:background="@drawable/messi"

        android:text="Radio button 3" />
</RadioGroup>


</androidx.constraintlayout.widget.ConstraintLayout>

secondActivity.java

package com.example.endsempracmad;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

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

    String selection = getIntent().getStringExtra("selection");
    TextView textView = findViewById(R.id.textView);
    textView.setText("Selected option: " + selection);

}
}

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView"
    tools:layout_editor_absoluteX="212dp"
    tools:layout_editor_absoluteY="113dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接