标签:
1.简介
RadioButton为单选按钮,当一个按钮被选中后,点击其他按钮无法使上一个按钮变为未选中状态。RadioGroup是可以容纳多个RadioButton的容器,
通过使用RadioGroup,可以实现每次只有一个处于按钮被选中状态。
2.构建
我们可以从From Widgets中选择单选按钮,构建图二所示界面。
XML代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="250dp"
android:text="@string/tx" >
</TextView>
<RadioGroup
android:id="@+id/rg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:text="@string/rb1"/>
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="fill_parent"
android:layout_height="74dp"
android:text="@string/rb2" />
</RadioGroup>
</RelativeLayout>
3.代码
public class Activity1 extends Activity {
private RadioButton rbutton1;
private RadioButton rbutton2;
private RadioGroup rgroup;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act1);
rbutton1 = (RadioButton) findViewById(R.id.radioButton1);
rbutton2 = (RadioButton) findViewById(R.id.radioButton2);
rgroup = (RadioGroup) findViewById(R.id.rg);
tv = (TextView) findViewById(R.id.textView);
//为RadioGroup设置监听器
rgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == rbutton1.getId()) {
DisplayToast("you have chosen " + rbutton1.getText());
} else {
DisplayToast("you have chosen " + rbutton2.getText());
}
}
});
}
//自定义位置Toast
public void DisplayToast(String string) {
//最后一项表示内容显示时间
Toast mToast = Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG);
//内容在底部显示,前一项表示左右移动,后一项表示上下移动
mToast.setGravity(Gravity.BOTTOM, 0, 200);
mToast.show();
}
4.效果
标签:
原文地址:http://www.cnblogs.com/jfl-xx/p/5175893.html