RadioGroup与RadioButton实例
*********
java文件
*********
package com.pms.myradiobutton;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class MyRadioButton extends Activity {
/*声明各个控件的引用*/
private RadioGroup rg;
private RadioButton rb1;
private TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*得到各个控件的引用*/
rg = (RadioGroup) findViewById(R.id.rg);
rb1 = (RadioButton) findViewById(R.id.rb1);
tv = (TextView) findViewById(R.id.tv);
/*为RadioGroup添加监听事件*/
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == rb1.getId())
{
tv.setText("回答正确!");
}
else
{
tv.setText("回答错误,赶紧把书翻回去重学!");
}
}
});
}
}
布局文件
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="android属于哪家公司?"
/>
<!-- 添加一个RadioGroup控件,垂直摆放 -->
<RadioGroup
android:id="@+id/rg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<RadioButton
android:id="@+id/rb1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="google"
/>
<RadioButton
android:id="@+id/rb2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="apple"
/>
<RadioButton
android:id="@+id/rb3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="microsoft"
/>
</RadioGroup>
</LinearLayout>
运行结果:
总结:
单选按钮注册监听器的方法:
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
});
判断是否选中方法getId()