首页 > 代码库 > Java-Android 之单选按钮的运用

Java-Android 之单选按钮的运用

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/text"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="单选按钮" /><RadioGroup     android:id="@+id/sex"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    >    <RadioButton        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text= "男"        ></RadioButton>   <RadioButton        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text= "女"        ></RadioButton></RadioGroup><Button    android:id="@+id/select"    android:text="选择"    android:layout_width="fill_parent"    android:layout_height="wrap_content"            android:topLeftRadius="5dip"               android:topRightRadius="5dip"               android:bottomLeftRadius="5dip"               android:bottomRightRadius="5dip"    ></Button>        </LinearLayout>

 MainActivity.java

package cn.szy.com;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.RadioButton;import android.widget.RadioGroup;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {    /** Called when the activity is first created. */	private RadioGroup group;	private Button button;	private TextView textView;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        group = (RadioGroup) this.findViewById(R.id.sex);        button  =(Button) this.findViewById(R.id.select);        textView = (TextView) this.findViewById(R.id.text);        button.setOnClickListener(new View.OnClickListener() {            public void onClick(View v) {                // Perform action on click            	int len = group.getChildCount();            	String msg = "您选择了";            	textView.setText(msg);            	//            	for(int i=0;i<len;i++){//            		RadioButton radiobutton  = (RadioButton) group.getChildAt(i);//            		if(radiobutton.isChecked()){//            			msg = radiobutton.getText().toString();//            			break;//            		}//            	}            	RadioButton radiobutton1  = (RadioButton) group.getChildAt(0);            	RadioButton radiobutton2  = (RadioButton) group.getChildAt(1);            	if(radiobutton1.isChecked()){            		Toast.makeText(MainActivity.this, "男", 1).show();            	}else if(radiobutton2.isChecked()){            		Toast.makeText(MainActivity.this, "女", 1).show();            	}            	            }        });    }}

 

Java-Android 之单选按钮的运用