RadioButton实现多选一
一、简介
二、RadioButton实现多选一方法
1、将多个RadioButton放在一个RadioGroup里面
1 <RadioGroup 2 android:id="@+id/radioGroup1"
3 android:layout_width="match_parent"
4 android:layout_height="wrap_content" >
5
6 <RadioButton
7 android:layout_width="wrap_content"
8 android:layout_height="wrap_content"
9 android:text="男"
10 android:textColor="#FFFFFF" />
11
12 <RadioButton
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:text="女"
16 android:textColor="#FFFFFF" />
17 </RadioGroup>
2、在RadioGroup里面取出每个RadioButton
1 public void onClick(View v) {
2 // TODO Auto-generated method stub
3 int len = radioGroup1.getChildCount();
4 for (int i = 0; i < len; i++) {
5 RadioButton radio = (RadioButton) radioGroup1.getChildAt(i);11 }
12 }
3、检查每个RadioButton是否被选取
1 if (radio.isChecked()) {
4 break;
5 }
4、取出被选取的那个RadioButton里面的值
1 Toast.makeText(Activity01.this, radio.getText(),
2 Toast.LENGTH_LONG).show();
三、代码实例
效果图:
代码:
fry.Activity01
1 package fry;
2
3 import com.example.RadioButtonDemo1.R;
4
5 import android.app.Activity;
6 import android.os.Bundle;
7 import android.view.View;
8 import android.view.View.OnClickListener;
9 import android.widget.Button;
10 import android.widget.RadioButton;
11 import android.widget.RadioGroup;
12 import android.widget.TextView;
13 import android.widget.Toast;
14
15 public class Activity01 extends Activity {
16 private Button btn_chooseGender;
17 private RadioGroup radioGroup1;
18 private TextView tv_answer;
19
20 @Override
21 protected void onCreate(Bundle savedInstanceState) {
22 // TODO Auto-generated method stub
23 super.onCreate(savedInstanceState);
24 setContentView(R.layout.activity01);
25
26 btn_chooseGender = (Button) findViewById(R.id.btn_chooseGender);
27 radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
28 tv_answer = (TextView) findViewById(R.id.tv_answer);
29 /*
30 * RadioButton实现多选一方法
31 * 1、将多个RadioButton放在一个RadioGroup里面
32 * 2、在RadioGroup里面取出每个RadioButton
33 * 3、检查每个RadioButton是否被选取
34 * 4、取出被选取的那个RadioButton里面的值
35 */
36 btn_chooseGender.setOnClickListener(new OnClickListener() {
37
38 @Override
39 public void onClick(View v) {
40 // TODO Auto-generated method stub
41 int len = radioGroup1.getChildCount();
42 for (int i = 0; i < len; i++) {
43 RadioButton radio = (RadioButton) radioGroup1.getChildAt(i);
44 if (radio.isChecked()) {
45 Toast.makeText(Activity01.this, radio.getText(),
46 Toast.LENGTH_LONG).show();
47 break;
48 }
49 }
50 }
51 });
52 }
53 }
/RadioButtonDemo1/res/layout/activity01.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:background="@android:color/black"
6 android:orientation="vertical" >
7
8 <TextView
9 android:layout_width="match_parent"
10 android:layout_height="wrap_content"
11 andr