注意事项:当使用默认选中标签:check时,必须要给标签加id,否则失效。
这个没什么,挺简单的,就记录一下代码【监听事件】
package com.example.app02; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class RadioButtonActivity extends AppCompatActivity { private RadioGroup mRg1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_radio_button); mRg1=findViewById(R.id.rg_1); mRg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { RadioButton radioButton=radioGroup.findViewById(i); Toast.makeText(RadioButtonActivity.this, radioButton.getText(), Toast.LENGTH_SHORT).show(); } }); } }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="15dp"> <RadioGroup android:id="@+id/rg_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton android:id="@+id/rb_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="男" android:checked="true" android:textSize="25sp" android:textColor="#FF0000"/> <RadioButton android:id="@+id/rb_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="女" android:textColor="#FF0000" android:textSize="25dp"/> </RadioGroup> <RadioGroup android:id="@+id/rg_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_below="@id/rg_1" android:layout_marginTop="50dp"> <RadioButton android:id="@+id/rb_3" android:layout_width="60dp" android:layout_height="30dp" android:button="@null" android:text="男" android:checked="true" android:textSize="25sp" android:textColor="#fff" android:background="@drawable/bg_pink"/> <RadioButton android:id="@+id/rb_4" android:layout_width="60dp" android:layout_height="30dp" android:text="女" android:textColor="#fff" android:textSize="25dp" android:button="@null" android:layout_marginLeft="10dp" android:background="@drawable/bg_pink"/> </RadioGroup> </RelativeLayout>
标签:Toast,widget,day05,RadioButton,RadioGroup,import,Android,android From: https://www.cnblogs.com/gbrr/p/17031566.html