单选按钮RadioButton在Android平台上也应用的非常多,比如一些选择项的时候,会用到单选按钮,实现单选按钮由两部分组成,也就是RadioButton和RadioGroup配合使用
RadioButton的单选按钮;
RadioGroup是单选组合框,用于将RadioButton框起来;
在没有RadioGroup的情况下,RadioButton可以全部都选中;
当多个RadioButton被RadioGroup包含的情况下,RadioButton只可以选择一个;
RadioButton的单选按钮;
RadioGroup是单选组合框,用于将RadioButton框起来;
在没有RadioGroup的情况下,RadioButton可以全部都选中;
当多个RadioButton被RadioGroup包含的情况下,RadioButton只可以选择一个;
注意:单选按钮的事件监听用setOnCheckedChangeListener来对单选按钮进行监听
RadioButton效果:
本程序的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"
- >
- <RadioGroup
- android:id="@+id/radioGroup"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="vertical">
- <RadioButton
- android:id="@+id/radioBlue"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="blue"/>
- <RadioButton
- android:id="@+id/radioRed"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="red"/>
- </RadioGroup>
- </LinearLayout>
RadioButton事件响应setOnCheckedChangeListener
本程序的java源码:
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.RadioGroup;
- import android.widget.Toast;
- public class RadioButtonActivity extends Activity
- {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- final RadioGroup group = (RadioGroup)findViewById(R.id.radioGroup);
- group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
- {
- @Override
- public void onCheckedChanged(RadioGroup group, int checkedId)
- {
- switch(checkedId)
- {
- case R.id.radioBlue:
- Toast.makeText(getApplicationContext(), "你选中了蓝色按钮", Toast.LENGTH_LONG).show();
- break;
- case R.id.radioRed:
- Toast.makeText(getApplicationContext(), "你选中了红色按钮", Toast.LENGTH_LONG).show();
- break;
- }
- }
- });
- }
- }