layout文件:
<LinearLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请输入性别" />
<RadioGroup
android:id="@+id/sex"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/male"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="男"
/>
<RadioButton
android:id="@+id/female"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="女"
/>
</RadioGroup>
</LinearLayout>
MainActivity.java文件:
package com.example.danxuananniu;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView txt = null;
private RadioGroup sex = null;
private RadioButton male = null;
private RadioButton female = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.txt = (TextView) super.findViewById(R.id.txt);
this.sex = (RadioGroup) super.findViewById(R.id.sex);
this.male = (RadioButton) super.findViewById(R.id.male);
this.female = (RadioButton) super.findViewById(R.id.female);
}
private class MyOnCheckedChangeListener implements OnCheckedChangeListener{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO 自动生成的方法存根
String temp = null;
if(MainActivity.this.male.getId() ==checkedId){
temp = MainActivity.this.male.getText().toString();
}
if(MainActivity.this.female.getId() ==checkedId){
temp = MainActivity.this.female.getText().toString();
}
MainActivity.this.txt.setText(temp);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}