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

发布于 2024-11-25 15:18:08 字数 1361 浏览 1 评论 0原文

根据我的理解,要确定一个复选框是否被“单击”并确定它是否被选中,可以使用如下代码:

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 上?

From my understanding, to determine if a checkbox is "clicked" and find if it's checked or not, code such as the following can be used:

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"); 
        } 
    }

However, I am unable to work out the logic on how to do the above for a radiogroup.

Here is the xml for my RadioGroup:

<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>

Question: Do i need to setup another listener, or will the listener already there also "register" this group?

Also, should the listener be set up on the RadioGroup or the RadioButton?

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

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

发布评论

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

评论(6

看海 2024-12-02 15:18:08

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

// 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());
        }
    }
});

This is how you get the checked radiobutton:

// 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());

To use the listener, you do this:

// 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());
        }
    }
});
遥远的绿洲 2024-12-02 15:18:08

应该是这样的。

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

            }
        }

    });

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

It should be something like this.

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

            }
        }

    });

Based on the checkedId, you would know which of the radiobutton has been clicked and then use your above code to figure out if its checked or unchecked. This is homework. ;)

镜花水月 2024-12-02 15:18:08

使用 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;
        }
      }
    });

Using Switch is better:

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;
        }
      }
    });
能怎样 2024-12-02 15:18:08
//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;
}
}
//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;
}
}
倾其所爱 2024-12-02 15:18:08

如果您想查看单选按钮组中选中或选择的单选按钮,请使用以下命令:

//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
        }
    });

If you want to see which radio Button is checked or selected in the radio group then use the following:

//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
        }
    });
萌能量女王 2024-12-02 15:18:08

我的 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>

My 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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文