<?xml version="1.0" encoding="utf-8"?> <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:layout_width="fill_parent" android:layout_height="wrap_content" android:text="性别:" /> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/sex"> <RadioButton android:id="@+id/b1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="男"/> <RadioButton android:id="@+id/b2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="女"/> </RadioGroup> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="确认"/> </LinearLayout>
package com.android.RadioButton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class Main extends Activity {
private Button button;
private RadioGroup group;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)this.findViewById(R.id.button);
group = (RadioGroup)this.findViewById(R.id.sex);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int len = group.getChildCount();//获得单选按钮组的选线个数
String msg = "";
for (int i=0;i<len;i++){
//找到所有的radiobutton
RadioButton radioButton = (RadioButton)group.getChildAt(i);
//判断radiobutton是否被选中
if(radioButton.isChecked()){
msg = radioButton.getText().toString();
break;
}
}
Toast.makeText(Main.this, msg, 1).show();
}
});
}
}
RadioGroup
公共方法
public void addView (View child, int index, ViewGroup.LayoutParams params)
使用指定的布局参数添加一个子视图
参数
child 所要添加的子视图
index 将要添加子视图的位置
params 所要添加的子视图的布局参数
public void check (int id)
如果传递-1作为指定的选择标识符来清除单选按钮组的勾选状态,相当于调用clearCheck()操作
参数
id 该组中所要勾选的单选按钮的唯一标识符(id)
参见
getCheckedRadioButtonId()
clearCheck()
public void clearCheck ()
清除当前的选择状态,当选择状态被清除,则单选按钮组里面的所有单选按钮将取消勾选状态,getCheckedRadioButtonId()将返回null
参见
check(int)
getCheckedRadioButtonId()
public RadioGroup.LayoutParams generateLayoutParams (AttributeSet attrs)
基于提供的属性集合返回一个新的布局参数集合
参数
attrs 用于生成布局参数的属性
返回值
返回一个ViewGroup.LayoutParams或其子类的实例
public int getCheckedRadioButtonId ()
返回该单选按钮组中所选择的单选按钮的标识ID,如果没有勾选则返回-1
返回值
返回该单选按钮组中所选择的单选按钮的标识ID
参见
check(int)
clearCheck()
public void setOnCheckedChangeListener (RadioGroup.OnCheckedChangeListener listener)
注册一个当该单选按钮组中的单选按钮勾选状态发生改变时所要调用的回调函数
参数
listener 当单选按钮勾选状态发生改变时所要调用的回调函数
public void setOnHierarchyChangeListener (ViewGroup.OnHierarchyChangeListener listener)
注册一个当子内容添加到该视图或者从该视图中移除时所要调用的回调函数
参数
listener 当层次结构发生改变时所要调用的回调函数