Android RadioButton 单选按钮

RadioGroup 单选按钮组, 可以包含多个单选按钮,当单选按钮选中状态改变时会触发setOnCheckedChangeListener


package shortcut.song.com.myapplication;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

public class RadioButtonActivity extends AppCompatActivity {
    RadioGroup mRadioGroup;
    RelativeLayout mRelativeLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_button);

        mRadioGroup = (RadioGroup)findViewById(R.id.radiogroup1);
        mRelativeLayout = (RelativeLayout)findViewById(R.id.activity_radio_button);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId)
                {
                    case R.id.radio1:
                        mRelativeLayout.setBackgroundColor(Color.RED);
                        break;
                    case R.id.radio2:
                        mRelativeLayout.setBackgroundColor(Color.GREEN);
                        break;
                    case R.id.radio3:
                        mRelativeLayout.setBackgroundColor(Color.BLUE);
                        break;
                }
            }
        });

    }
}

layout布局,包含了一个RadioGroup,和三个RadioButton

xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_radio_button"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="shortcut.song.com.myapplication.RadioButtonActivity">
    <RadioGroup
        android:id="@+id/radiogroup1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="红色"
            />
        <RadioButton
           android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="绿色"
            />
        <RadioButton
            android:id="@+id/radio3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="蓝色"
            />
    RadioGroup>
RelativeLayout>


你可能感兴趣的:(Android)