赞
踩
先来个例子感受一下
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
- android:layout_height="fill_parent" tools:context=".MainActivity"
- android:orientation="horizontal"
- >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="性别:"
- android:height="50px"/>
- <RadioGroup
- android:id="@+id/radioGroup1"
- android:orientation="horizontal"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- <RadioButton
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/radio0"
- android:text="男"
- android:checked="true"/>
- <RadioButton
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/radio1"
- android:text="女"/>
- </RadioGroup>
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/button1"
- android:text="提交"/>
- </LinearLayout>
1、在改变单选按钮组的值时获取
- RadioGroup sex = (RadioGroup)findViewById(R.id.radioGroup1);
- sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(RadioGroup group, int checkedId) {
- RadioButton r = (RadioButton)findViewById(checkedId);
- r.getText(); //获取被选中的单选按钮的值
- }
- });
2、单击其他按钮时获
- final RadioGroup sex = (RadioGroup)findViewById(R.id.radioGroup1);
- Button button = (Button)findViewById(R.id.button1);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- for(int i=0;i<sex.getChildCount();i++){
- RadioButton r = (RadioButton)sex.getChildAt(i); //根据索引值获取单选按钮
- if(r.isChecked()){ //判断单选按钮是否被选中
- r.getText(); //获取被选中的单选按钮的值
- break; //跳出for循环
- }
- }
- }
- });
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- final RadioGroup sex = (RadioGroup)findViewById(R.id.radioGroup1);
- sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(RadioGroup group, int checkedId) {
- RadioButton r = (RadioButton)findViewById(checkedId);//获取被选择的单选按钮
- Log.i("单选按钮","您选择的是:"+r.getText());
- }
- });
- Button button = (Button)findViewById(R.id.button1); //获取提交按钮
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- for(int i=0;i<sex.getChildCount();i++){
- RadioButton r = (RadioButton)sex.getChildAt(i);
- if(r.isChecked()){ //判断单选按钮是否被选中
- Log.i("单选按钮","性别:"+r.getText());
- break; //跳出for循环
- }
- }
- }
- });
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。