RadioButton的创建、监听与继承

概述

RadioButton是单选按钮,点击后选中,再次点击不可取消选中。RadioButton继承自CompoundButton(复合按钮)。RadioButton组必须在RadioGroup视图(RadioGroup继承自LinearLayout)中使用。RadioButton组中只有最后被点击的RadioButton处于选中状态,其余RadioButton则处于未选中状态。

RadioButton的创建

使用xml布局创建

 使用xml布局创建RadioButton的核心在于findviewById()布局文件。注意RadioButton组必须在RadioGroup中使用。
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout...>
    ...
    <RadioGroup
        android:id="@+id/rg_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <RadioButton
            android:id="@+id/rb_1"
            android:layout_width="match_parent"
            android:height="wrap_content"
            android:text="Java"/>
        <RadioButton
            android:id="@+id/rb_2"
            android:layout_width="match_parent"
            android:height="wrap_content"
            android:text="C++"/>
        <RadioButton
            android:id="@+id/rb_3"
            android:layout_width="match_parent"
            android:height="wrap_content"
            android:text="C#"/>        
    </RadioGroup>  
    ...
</LinearLayout>

MainActivity.java

import...
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //remove title bar and status bar in activity 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        RadioGroup rg_1=new (RadioGroup)findviewById(R.id.rg_1);
        RadioButton rb_1=new (RadioButton)findviewById(R.id.rb_1);
        RadioButton rb_2=new (RadioButton)findviewById(R.id.rb_2);  
        RadioButton rb_3=new (RadioButton)findviewById(R.id.rb_3);  
        ...        
    }
}

使用Java代码创建

 使用Java代码创建RadioButton的步骤与使用Java代码创建Button的步骤基本一致(详见Button的创建、监听与继承):
 ①使用构造函数RadioGroup(Context context)创建RadioGroup对象并设置必要属性参数

RadioGroup rg_1=new RadioGroup(this);
LinearLayout.LayoutParams params_rg=new LinearLayout.LayoutParams(
                              ViewGroup.LayoutParams.MATCH_PARENT,
                              ViewGroup.LayoutParams.WRAP_CONTENT);
rg_1.setLayoutParams(params_rg);

 ②将RadioGroup对象添加至目标ViewGroup

//find ViewGroup in xml file
LinearLayout layout_main=(LinearLayout)findviewById(R.id.layout_main);
layout_main.addView(rg_1);

 ③为RadioGroup设置id、外观等参数

rg_1.setId(R.id.rg_1);
rg_1.setBackgroundResource(R.drawable.drawablefile);
...

 ④使用构造函数RadioButton(Context context)创建RadioButton对象并设置必要属性参数

RadioButton rb_1=new RadioButton(this);
RadioButton rb_2=new RadioButton(this);
RadioButton rb_3=new RadioButton(this);
...
LinearLayout.LayoutParams params_rb=new LinearLayout.LayoutParams(
                              ViewGroup.LayoutParams.MATCH_PARENT,
                              ViewGroup.LayoutParams.WRAP_CONTENT);
rb_1.setLayoutParams(params_rb);
rb_2.setLayoutParams(params_rb);
rb_3.setLayoutParams(params_rb);
...

 ⑤将RadioButton添加到之前创建的RadioGroup对象

rg_1.addView(rb_1);
rg_1.addView(rb_2);
rg_1.addView(rb_3);
...

 ⑥为RadioButton设置id、外观等参数

rb_1.setId(R.id.rb_1);
rb_1.setBackgroundResource(R.drawable.drawablefile);
rb_2.setId(R.id.rb_2);
rb_2.setBackgroundResource(R.drawable.drawablefile);
rb_3.setId(R.id.rb_3);
rb_3.setBackgroundResource(R.drawable.drawablefile);
...

 ⑦使用目标ViewGroup对象的removeView()方法从目标ViewGroup移除RadioButton

rg_1.removeView(rb_1);

RadioButton配合ScrollView使用

 当ViewGroup尺寸有限而内容View可能会超过ViewGroup尺寸时,可以使用ScrollView装盛View以实现滚动显示。但是由于RadioButton组必须在RadioGroup中使用,再配合ScrollView使用时需要注意有不同之处,正确的做法是:RadioButton in RadioGroupRadioGroup in ScrollView;而并非:RadioButton in ScrollViewScrollView in RadioGroup

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:orientation="vertical">
    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <RadioButton
            android:id="@+id/rb_1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Java"/>
        <RadioButton
            android:id="@+id/rb_2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="C++"/>
        <RadioButton
            android:id="@+id/rb_3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="C#"/>        
    </RadioGroup>
</ScrollView>

RadioButton的监听

 与RadioButton相关的监听器为OnCheckedChangeListener,然而RadioButton不可注册OnCheckedChangeListener。RadioButton的监听,需要由RadioButton所在的RadioGroup注册OnCheckedChangeListener
 充当RadioGroup的OnCheckedChangeListener的对象类必须实现RadioGroup.OnCheckedChangeListener接口。

public class MyCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
    ...
}

 RadioButton设置监听器的方式有:
 ①当前Activity类实现RadioGroup.OnCheckedChangeListener接口
 ②内部类实现RadioGroup.OnCheckedChangeListener接口
 ③匿名内部类实现RadioGroup.OnCheckedChangeListener接口
 ④外部类实现RadioGroup.OnCheckedChangeListener接口
 充当OnCheckedChangeListener的对象类必须重写onCheckedChanged()方法:

public class MyCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
    ...
    @Override
    public void onCheckedChanged(RadioGroup group,int checkedId) {
        if(group.getId()==R.id.rg_1) {
            switch(checkedId) {
                case R.id.rb_1:
                    ...
                    break;
                case R.id.rb_2:
                    ...
                    break;
                ...            
            }
        }
        else if(group.getId()==R.id.rg_2) {...}
        ...
    }
    ...
}

 每点击一次未选中的RadioButton按钮就会触发onCheckedChanged()方法。使用group.getId()方法判断响应点击的RadioGroup;使用checkedId判断响应点击的RadioGroup中被选中的RadioButton

RadioButton的常用属性

android:checked
 RadioButton的当前选中状态。属性值为true/false。为true当前状态为被选中;为false当前状态为未被选中。对应的设置方法为setChecked(boolean checked)
android:button
 RadioButton左侧按钮的图形或颜色。属性值可以是RGB888ARGB值,也可以是图形图片资源。对应的设置方法为setButtonDrawable(R.drawable.drawablefile)
android:background
 RadioButton右侧文字部分的背景。属性值可以是RGB888ARGB值,也可以是图形图片资源。对应的设置方法为setBackground()setBackgroundColor()
android:gravity
 RadioButton文字的内部对齐方式。属性值:top(顶对齐)bottom(底对齐)left(左对齐)right(右对齐)center(居中)。对应的设置方法为setGravity()
android:scaleX/android:scaleY
 RadioButton的X/Y方向的尺寸缩放。属性值为0~1。对应的设置方法为setScaleX(float scaleX)/setScaleY(float scaleY)

RadioButton的继承

 自定义RadioButton时会用到RadioButton的继承。AndroidStudio要求使用AppCompatRadioButton代替RadioButton用以自定义RadioButton类的继承。对于开发者而言,自定义RadioButton中最有意义的方法是构造函数onTouchEvent()
 以下以简单实例展示RadioButton的继承:
rb_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size
        android:width="200dp"
        android:height="25dp"/>
    <solid
        android:color="#50f0f0f0"/>
    <corners
        android:radius="10dp"/>
    <stroke
        android:width="1dp"
        android:color="#ff000000"/>
</shape>

rb_id

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="rg_1" type="id"/>
    <item name="rb_1" type="id"/>
    <item name="rb_2" type="id"/>
    <item name="rb_3" type="id"/>
</resources>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    ...
    android:id="@+id/layout_main"
    ...>
    <TextView
        android:id="@+id/tv_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/rb_shape"
        android:text="hello"/>
    ...    
</LinearLayout>

MyRadioButton.java

import...
import androidx.appcompat.widget.AppCompatRadioButton;
public class MyRadioButton extends AppCompatRadioButton {
    //constructors
    public MyRadioButton(Context context) {
        super(context);
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //set necessary params        
        this.setLayoutParams(params);
        //set background
        this.setBackgroundResource(R.drawable.rb_shape);
    }

    public MyRadioButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //set necessary params 
        this.setLayoutParams(params);
        //set background
        this.setBackgroundResource(R.drawable.rb_shape);
    }

    public MyRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //set necessary params 
        this.setLayoutParams(params);
        //set background
        this.setBackgroundResource(R.drawable.rb_shape);
    }
}

MainActivity.java

public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener {
    
    private TextView tv_1=(TextView)findviewById(R.id.tv_1);
    
    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //remove title bar and status bar in activity 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
                
        LinearLayout layout_main=new (LinearLayout)findviewById(R.id.layout_main);
        
        
        RadioGroup rg_1=new RadioGroup(this);
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
                                   ViewGroup.LayoutParams.MATCH_PARENT,
                                   ViewGroup.LayoutParams.WRAP_CONTENT);
        rg_1.setLayoutParams(params);
        layout_main.addView(rg_1);
        rg_1.setId(R.id.rg_1);
        
        MyRadioButton rb_1=new MyRadioButton(this);
        MyRadioButton rb_2=new MyRadioButton(this);
        MyRadioButton rb_3=new MyRadioButton(this);
        rg_1.addView(rb_1);
        rg_1.addView(rb_2);
        rg_1.addView(rb_3);
        
        rb_1.setId(R.id.rb_1);
        rb_1.setText("Java");
        rb_1.setOnCheckedChangeListener(this);
        
        rb_2.setId(R.id.rb_2);
        rb_2.setText("C++");
        rb_2.setOnCheckedChangeListener(this);
        
        rb_3.setId(R.id.rb_3);
        rb_3.setText("Python");
        rb_3.setOnCheckedChangeListener(this);
    }
    
    @Override 
    public void onCheckeChanged(RadioGroup group,int checkedId) {
        if(group.getId==R.id.rg_1) {
            switch(checkedId) {
                case R.id.rb_1:
                    tv_1.setText("you choosed Java");
                    break;
                case R.id.rb_2:
                    tv_1.setText("you choosed C++");
                    break;
                case R.id.rb_3:
                    tv_1.setText("you choosed Python");
                    break;        
            }
        }
        
    }
    
}

欢迎指正
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章