其他分享
首页 > 其他分享> > Android Studio 监听Radiogroup 并消息提示选中的选项

Android Studio 监听Radiogroup 并消息提示选中的选项

作者:互联网

布局界面代码:

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

    <RadioGroup
        android:id="@+id/sex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/sex1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="男" />

        <RadioButton
            android:id="@+id/sex2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="50dp"
            android:text="女" />
    </RadioGroup>
</RelativeLayout>

 

 java代码:

public class MainActivity extends AppCompatActivity {
    private RadioGroup sexgp;
    private String selSext;

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

        //获取radiongroup对象
        sexgp = (RadioGroup) findViewById(R.id.sex);

        //通过radiogroup的setoncheckedlistener方法注册监听事件
        //在监听事件中创建oncheckedlistener 在重写oncheckedchanged方法
        sexgp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //获取被选中的radiobutton的id
                RadioButton rcheck = (RadioButton) findViewById(checkedId);
                //获取
                String checkText = rcheck.getText().toString();
                Toast.makeText(MainActivity.this, "您选中的是:" + checkText, Toast.LENGTH_SHORT).show();

            }
        });
    }
}

模拟器模拟效果:

 

标签:Toast,RadioGroup,private,Studio,选中,Radiogroup,Android,sexgp,监听
来源: https://blog.csdn.net/qq_33168558/article/details/122154676