<RadioGroup> <RadioButton ... /> <RadioButton ... /> ... </RadioGroup>
如下面所示的例子: 这是在activity_main.xml中对RadioGroup的布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <RadioGroup android:id="@+id/radiogroup" android:layout_width="wrap_content" android:layout_height="fill_parent" android:orientation="vertical" android:layout_below="@id/tv" > <RadioButton android:id="@+id/radiobutton1" android:layout_width="wrap_content" android:text="@string/radiobutton1" android:checked="true" /> <RadioButton android:id="@+id/radiobutton2" android:layout_width="wrap_content" android:text="@string/radiobutton2" /> <RadioButton android:id="@+id/radiobutton3" android:layout_width="wrap_content" android:text="@string/radiobutton3" /> <RadioButton android:id="@+id/radiobutton4" android:layout_width="wrap_content" android:text="@string/radiobutton4" /> </RadioGroup> </RelativeLayout> 这是在MainActivity.java中的代码:package com.cn.rdiobuttontest; import android.app.Activity; import android.os.Bundle; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RadioGroup radiogroup = (RadioGroup)findViewById(R.id.radiogroup); radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub if(checkedId==R.id.radiobutton2) { Toast.makeText(getApplicationContext(), "恭喜您,选择正确!",Toast.LENGTH_LONG).show(); }else { Toast.makeText(getApplicationContext(), "对不起,您选择错误", Toast.LENGTH_SHORT).show(); } } }); } }
根据代码当选中Linux选项时会出现一个Toast框“恭喜您,选择正确!”第一个模拟器解图,选择其它选项会出现另一个Toast框“对不起,您选择错误”
第二个模拟器解图。
RadioButton点击事件
最新推荐文章于 2024-09-22 16:14:08 发布