RadioGroup组与onCheckedChanged事件

效果图:

 

Radio

 

第一步:建立Android工程 Test6

 

第二步:编写string.xml

 

<string name="app_name">RadioApp</string>
<string name="tr_radio_op1">帅哥</string>
<string name="tr_radio_op2">美女</string>
<string name="str_radio_question1">请问你是?</string>

 

 

第三步:编写main.xml

 

<TextView 
        android:id="@+id/myTextView" 
        android:layout_width="fill_parent"
        android:layout_height="49px"                             
        android:text="@string/str_radio_question1"
        android:textSize="30sp" />
    <!-- 建立一个RadioGroup -->
<RadioGroup 
        android:id="@+id/myRadioButton"
        android:layout_width="137px" 
        android:layout_height="216px"
        android:orientation="vertical">
       <!-- 第一个RadioButton -->
       <RadioButton 
               android:id="@+id/myRadioButton1"
               android:layout_width="wrap_content"  
               android:layout_height="wrap_content"
               android:text="@string/tr_radio_op1" />
       <!--  第二个RadioButton-->
       <RadioButton 
               android:id="@+id/myRadioButton2"
               android:layout_width="wrap_content"   
               android:layout_height="wrap_content"
               android:text="@string/tr_radio_op2" />
</RadioGroup>

 

 

第三步:编写Activity子类 RadioDemo

 

package com.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class RadioDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final TextView tv=(TextView)findViewById(R.id.myTextView);
        
        RadioGroup rg=(RadioGroup)findViewById(R.id.myRadioButton);
        
        final RadioButton rb1=(RadioButton)findViewById(R.id.myRadioButton1);
        
        final RadioButton rb2=(RadioButton)findViewById(R.id.myRadioButton2);
        
        rg.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			public void onCheckedChanged(RadioGroup arg0, int checkedId) {
				
				if(checkedId==rb1.getId()){
					
					tv.setText("您选在的是:"+rb1.getText().toString());	
					
				}
				
				if(checkedId==rb2.getId()){
					
					tv.setText("您选择的是:"+rb2.getText().toString());
					
				}
				
			}
        	
        });
    }
}

 

 

你可能感兴趣的:(xml,android,OS)