布局文件main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Sex">
<TextView
android:id="@+id/show"
android:textSize="20px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="你的性别是:" />
<RadioGroup
android:id="@+id/sex"
android:orientation="vertical"
android:checkedButton="@+id/male"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/male"
android:text="男"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<RadioButton
android:id="@+id/female"
android:text="女"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RadioGroup>
</LinearLayout>
定义Activity程序
package com.example.lenovo.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class Sex extends AppCompatActivity {
private TextView show ;
private RadioGroup sex ;
private RadioButton male ;
private RadioButton female ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.show = (TextView) super.findViewById(R.id.show);
this.sex = (RadioGroup) super.findViewById(R.id.sex);
this.male = (RadioButton) super.findViewById(R.id.male);
this.female = (RadioButton) super.findViewById(R.id.female);
this.sex.setOnCheckedChangeListener(new OnCheckedChangeListenerImpl());
}
private class OnCheckedChangeListenerImpl implements RadioGroup.OnCheckedChangeListener {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
String temp = null;
if (Sex.this.male.getId()==checkedId){
temp = Sex.this.male.getText().toString();
}
if (Sex.this.female.getId()==checkedId){
temp = Sex.this.female.getText().toString();
}
Sex.this.show.setText("你的性别是:"+temp);
}
}
}