安卓课程十八 RadioButton单选按钮的使用

安卓课程十八 RadioButton单选按钮的使用:

     具体内容实现查看网页:http://sarin.iteye.com/blog/1636484

activity_main.xml

RadioGroup android:id="@+id/idGroup" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
       
        android:orientation="horizontal">
        
        <RadioButton android:layout_width="wrap_content" 
            android:id="@+id/radio_boy"
            android:layout_height="wrap_content" 
            android:text="@string/sex_boy"
            android:checked="true"
          
            />
        <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" 
            android:id="@+id/radio_girl"
            android:text="@string/sex_girl"
            />
    </RadioGroup>
    <Button 
       android:layout_width="fill_parent" android:layout_height="wrap_content" 
       android:text="@string/selectBtn"
       android:id="@+id/selectBtn" 
        />

 MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {

	private Button btn;
	private RadioGroup radioGroup;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		radioGroup = (RadioGroup) this.findViewById(R.id.idGroup);
		btn = (Button) this.findViewById(R.id.selectBtn);
		
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				int radioCount = radioGroup.getChildCount();
				RadioButton radioButton;
				String msg = "";
				for (int i = 0; i < radioCount; i++) {
					radioButton =(RadioButton) radioGroup.getChildAt(i) ;
					if(radioButton.isChecked()){
						msg = radioButton.getText().toString();
						break;
					}
				}
				Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
			}
		});
	}

 

}

 

你可能感兴趣的:(RadioButton)