Android 单选框RadioGrop的使用。里面添加的是RadioButton
package com.radiodemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
/*************************************
* 单选框RadioButton的使用
*
* 1.定义见布局文件 2.事件的添加方法
*
***********************************/
private TextView textView;
private RadioGroup radioGroup;
private RadioButton radioButton1, radioButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 关联布局中的控件
textView = (TextView) findViewById(R.id.textView);// 用来显示选择
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioButton1 = (RadioButton) findViewById(R.id.radioButton1);
radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
radioGroup.setOnCheckedChangeListener(mChangeListener);
}
// 响应事件的函数。
private RadioGroup.OnCheckedChangeListener mChangeListener = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (radioButton1.getId() == checkedId) {
textView.setText(radioButton1.getText());
} else {
textView.setText(radioButton2.getText());
}
}
};
@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;
}
}
布局文件main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请问你是谁" />
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男的" >
</RadioButton>
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女的" >
</RadioButton>
</RadioGroup>
</LinearLayout>