Android控件与布局——基础控件RadioButton

        最近在用原生的控件和布局绘制一些界面并使用,虽然这些都是Android基本知识,但是有的时候真的感觉力不从心,感觉有必要对Android常用的控件和布局做一个系统的了解。后续一个月甚至更多的时间都会围绕这个主题展开,毕竟这里面还是有不少高级控件的,我也会尽量结合应用深入的进行了解。

项目GitHub地址入口

上一篇:CheckBox       下一篇:CheckedTextView

今天,我们的主题是基础控件RadioButton。在开始之前,我们还是以官方文档为开端来开始我们的讲解,下面是Android文档中对RadioButton的简介:

* <p>
* A radio button is a two-states button that can be either checked or
* unchecked. When the radio button is unchecked, the user can press or click it
* to check it. However, contrary to a {@link android.widget.CheckBox}, a radio
* button cannot be unchecked by the user once checked.
* </p>

看过上一篇文章的应该可以了解到,这个和我们的CheckBox是十分类似的,不同的点在于,这个控件可以由非选中状态通过点击事件转为选中状态,但是不能通过点击实现逆向的状态转换,一个默认样式RadioButton控件的非选中和选中状态如下:

其组成和CheckBox一样,我们同样可以分别对其中的字体和Button进行设置,实现达到和CheckBox一样的效果。在上面我们在简介中得知,这个控件能通过点击事件实现的效果如下(不能逆向改变状态):

接下来,我们对其基本属性进行设置,改变一下它的样式:

 

下面我们就结合一个小例子来实际的应用一下,这个小例子就是实现多项单选功能,运行的效果如下:

布局文件与控制逻辑如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="aoto.com.commonwidgetandlayout.basic_widget.radioButton.RadioButtonActivity">

<TextView
    android:layout_marginTop="20dp"
    android:textSize="20sp"
    android:text="请选择您最爱的职业:"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    <RadioButton
        android:textSize="25sp"
        android:id="@+id/radio_button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginStart="16dp"
        android:layout_marginTop="20dp"
        android:text="程序员" />

    <RadioButton
        android:textSize="25sp"
        android:id="@+id/radio_button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginStart="16dp"
        android:layout_marginTop="11dp"
        android:text="政治家" />
    <RadioButton
        android:textSize="25sp"
        android:id="@+id/radio_button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginStart="16dp"
        android:layout_marginTop="11dp"
        android:text="富二代" />
</LinearLayout>
package aoto.com.commonwidgetandlayout.basic_widget.radioButton;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.RadioButton;

import aoto.com.commonwidgetandlayout.R;

/**
 * @author why
 * @date 2019-5-13 20:44:28
 */
public class RadioButtonActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    private static final String TAG = "RadioButtonActivityWhy";
    RadioButton radioButton1;
    RadioButton radioButton2;
    RadioButton radioButton3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_button);
        radioButton1=findViewById(R.id.radio_button1);
        radioButton2=findViewById(R.id.radio_button2);
        radioButton3=findViewById(R.id.radio_button3);

        radioButton1.setOnCheckedChangeListener(this);
        radioButton2.setOnCheckedChangeListener(this);
        radioButton3.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            disableOthers(buttonView.getId());
            Log.e(TAG, "您最喜欢的职业是: "+buttonView.getText().toString() );
            buttonView.setTextColor(getResources().getColor(R.color.colorPrimary));
        }
        else {
            buttonView.setTextColor(Color.BLACK);
        }
    }

    private void disableOthers(int viewId) {
        if(R.id.radio_button1!=viewId&&radioButton1.isChecked()){
            radioButton1.setChecked(false);
        }
        if(R.id.radio_button2!=viewId&&radioButton2.isChecked()){
            radioButton2.setChecked(false);
        }
        if(R.id.radio_button3!=viewId&&radioButton3.isChecked()){
            radioButton3.setChecked(false);
        }
    }
}

可见,我们为了实现一个单选功能做了很多逻辑控制,而这样的场景又非常多,没有关系,我们接着官方文档关于对其的介绍继续向下看:

* <p>
* Radio buttons are normally used together in a
* {@link android.widget.RadioGroup}. When several radio buttons live inside
* a radio group, checking one radio button unchecks all the others.</p>

说这个RadioButton经常会结合RadioGroup一起使用,实现的功能正是我们上面所要实现的多项单选功能的操作。那下面就来看看如何使用RadioGroup实现上述例子的功能:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="aoto.com.commonwidgetandlayout.basic_widget.radioButton.RadioButton2Activity">

    <TextView
        android:layout_marginLeft="40dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="请选择您最爱的职业:"
        android:textSize="20sp" />

    <RadioGroup
        android:id="@+id/job_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">

        <RadioButton
            android:id="@+id/radio_button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:text="程序员"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

        <RadioButton
            android:id="@+id/radio_button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="11dp"
            android:text="政治家"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

        <RadioButton
            android:id="@+id/radio_button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="11dp"
            android:text="富二代"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />
    </RadioGroup>
    <Button
        android:id="@+id/clear_all"
        android:text="都不喜欢"
        android:onClick="clearAll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

逻辑部分:

package aoto.com.commonwidgetandlayout.basic_widget.radioButton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import aoto.com.commonwidgetandlayout.R;

/**
 * @author why
 * @date 2019-5-13 21:43:42
 */
public class RadioButton2Activity extends AppCompatActivity {

    private static final String TAG = "RadioButton2ActivityWhy";
    RadioGroup radioGroup;
    RadioButton radioButton1;
    RadioButton radioButton2;
    RadioButton radioButton3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_button2);
        radioGroup=findViewById(R.id.job_list);
        radioButton1=findViewById(R.id.radio_button1);
        radioButton2=findViewById(R.id.radio_button2);
        radioButton3=findViewById(R.id.radio_button3);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                getYourFavorite(checkedId);
            }
        });
    }

    /**
     * 根据ID,执行相应的逻辑
     * @param buttonId
     */
    private void getYourFavorite(int buttonId){
        switch (buttonId){
            case R.id.radio_button1:
                if(radioButton1.isChecked()) {
                    Log.e(TAG, "你最爱的职业是: " + radioButton1.getText().toString());
                }
                break;
            case R.id.radio_button2:
                if(radioButton2.isChecked()) {
                    Log.e(TAG, "你最爱的职业是: " + radioButton2.getText().toString());
                }
                break;
            case R.id.radio_button3:
                if(radioButton3.isChecked()) {
                    Log.e(TAG, "你最爱的职业是: " + radioButton3.getText().toString());
                }
                break;
        }
    }

    /**
     * 清除选型
     * @param view
     */
    public void clearAll(View view){
      radioGroup.clearCheck();
    }
}

在布局部分,我们只需要把之前放置在布局中的RadioButton放置在RadioGroup中即可:

<RadioGroup
        android:id="@+id/job_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">

        <RadioButton
            android:id="@+id/radio_button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:text="程序员"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

        <RadioButton
            android:id="@+id/radio_button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="11dp"
            android:text="政治家"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

        <RadioButton
            android:id="@+id/radio_button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="11dp"
            android:text="富二代"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />
    </RadioGroup>

逻辑部分我们首先为RadioGroup设置状态变化监听

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                getYourFavorite(checkedId);
            }
        });

根据选择的RadioButton的ID执行具体的逻辑代码:

 /**
     * 根据ID,执行相应的逻辑
     * @param buttonId
     */
    private void getYourFavorite(int buttonId){
        switch (buttonId){
            case R.id.radio_button1:
                if(radioButton1.isChecked()) {
                    Log.e(TAG, "你最爱的职业是: " + radioButton1.getText().toString());
                }
                break;
            case R.id.radio_button2:
                if(radioButton2.isChecked()) {
                    Log.e(TAG, "你最爱的职业是: " + radioButton2.getText().toString());
                }
                break;
            case R.id.radio_button3:
                if(radioButton3.isChecked()) {
                    Log.e(TAG, "你最爱的职业是: " + radioButton3.getText().toString());
                }
                break;
        }
    }

注意到在这里我们只实现了数据的获取(RadioButton的文本内容),RadioGroup中的RadioButton之间的状态管理(单选)是RadioGroup内部自己管理的,这为我们节省很多的开发逻辑,也是我们用它的主要目的。此外,这里,我们还可以通过调用clearCheck()实现清除选择状态。

radioGroup.clearCheck()

运行结果如下所示:

同样,如果你觉得RadioButton中的Button样式不好看,你可以自定义一种,这里,我们还是选用上一篇中的样式代码,执行效果如下:

修改按钮样式是通过android:button属性:

 <RadioButton
            android:id="@+id/radio_button1"
            android:button="@drawable/check_box_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:text="程序员"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="25sp" />

其中的check_box_back.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/chosen"></item>
    <item android:state_checked="false" android:drawable="@drawable/non_chosen_big"></item>
</selector>

该控件的开源项目在网上找了一下,感觉没有什么比较好的,主要是因为它的封装程度已经很高了,如果只是想改动一下显示样式和逻辑,我们自己完全可以实现。好了,关于RadioButton到这里的简单介绍就介绍了。

上一篇:CheckBox       下一篇:CheckedTextView  

注:欢迎扫码关注

 

  • 12
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值