Android中RadioGroup组与onCheckedChanged事件

例子效果图

 

 

 

实现步骤

 

第一步:建Android 工程:RadioGroupDemo

                                                                   

第二步:编写Activity 的子类别:RadioGroupDemo,其程序代码如下:

 

package com.a3gs.radiogroup;

 

import android.app.Activity;

import android.os.Bundle;

import android.widget.RadioButton;

import android.widget.RadioGroup;

import android.widget.TextView;

 

public class RadioGroupDemo extends Activity {

    private TextView TV;

    private RadioGroup RG;

    private RadioButton RB1, RB2;

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

       

        TV = (TextView) findViewById(R.id.TV);

        RG = (RadioGroup) findViewById(R.id.RG);

        RB1 = (RadioButton) findViewById(R.id.rb1);

        RB2 = (RadioButton) findViewById(R.id.rb2);

       

        RG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){

 

           @Override

           public void onCheckedChanged(RadioGroup group, int checkedId) {

              // TODO Auto-generated method stub

              if(checkedId == RB1.getId()){

                  TV.setText("您所选择的是:" + RB1.getText().toString());

              }

              if(checkedId == RB2.getId()){

                  TV.setText("您所选择的是:" + RB2.getText().toString());

              }

           }

           

        });

    }

}

 

第三步:修改res/layout/main.xml,其代码如下:

 

xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<TextView 

    android:id="@+id/TV"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />

<RadioGroup

    android:id="@+id/RG"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:orientation="vertical"

    >

    <RadioButton

    android:id="@+id/rb1"

    android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/rbText1"

    />

    <RadioButton

    android:id="@+id/rb2"

    android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/rbText2"

    />

RadioGroup>

LinearLayout>

 

第四步:修改res/values/ strings.xml,其代码如下:

 

xml version="1.0" encoding="utf-8"?>

<resources>

    <string name="hello">Hello World, RadioGroupDemo!string>

    <string name="app_name">RadioGroupDemostring>

    <string name="rbText1">天使知识授理厂string>

    <string name="rbText2">www.a3gs.comstring>

resources>

你可能感兴趣的:(android)