天天看点

【Android 常见控件使用】RadioButton(单选按钮)&Checkbox(复选框)

文章目录

  • ​​RadioButton(单选按钮)&Checkbox(复选框)​​
  • ​​本节引言​​
  • ​​1.基本用法与事件处理​​
  • ​​1)RadioButton(单选按钮)​​
  • ​​2)CheckBox(复选框)​​
  • ​​2.自定义点击效果​​
  • ​​3.改变文字与选择框的相对位置​​
  • ​​4.修改文字与选择框的距离​​

RadioButton(单选按钮)&Checkbox(复选框)

本节引言

本节给大家带来的是Andoird基本UI控件中的RadioButton和Checkbox; 其实这两个控件有很多地方都是类似的,除了单选和多选,事件处理,其他的都是类似的! 另外还有一个ListView上Checkbox的错位的问题,我们会在ListView那一章对这个问题进行 解决,好的,开始本节内容~

1.基本用法与事件处理

1)RadioButton(单选按钮)

如题单选按钮,就是只能够选中一个,所以我们需要把RadioButton放到RadioGroup按钮组中,从而实现 单选功能!先熟悉下如何使用RadioButton,一个简单的性别选择的例子: 另外我们可以为外层RadioGroup设置orientation属性然后设置RadioButton的排列方式,是竖直还是水平~

效果图:

【Android 常见控件使用】RadioButton(单选按钮)&Checkbox(复选框)

PS:笔者的手机是Android 5.0.1的,这里的RadioButton相比起旧版本的RadioButton,稍微好看一点~

布局代码如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".basicItems.Button.RadioButtonActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="30dp"
        android:layout_marginTop="45dp"
        android:text="请选择性别:"
        android:textSize="24dp"
        android:textStyle="bold"/>

    <RadioGroup
        android:id="@+id/rg"
        android:layout_width="186dp"
        android:layout_height="129dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="174dp"
        android:layout_marginTop="38dp"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="0dp"
            android:layout_marginBottom="0dp"
            android:text="男"
            android:textSize="18dp" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="0dp"
            android:layout_marginBottom="0dp"
            android:text="女"
            android:textSize="18dp" />
    </RadioGroup>

    <Button
        android:id="@+id/btn_post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="33dp"
        android:layout_marginTop="114dp"
        android:text="提交"
        android:textSize="18dp"/>

</RelativeLayout>      

获得选中的值:

这里有三种法:

第一种是为RadioButton设置一个事件监听器setOnCheckChangeListener

例子代码如下:

RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);
//第一种获得单选按钮值的方法  
//为radioGroup设置一个监听器:setOnCheckedChanged()  
radgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        RadioButton radbtn = (RadioButton) findViewById(checkedId);
        Toast.makeText(getApplicationContext(), "按钮组值发生改变,你选了" + radbtn.getText(), Toast.LENGTH_LONG).show();
    }
});      

运行效果图:

【Android 常见控件使用】RadioButton(单选按钮)&amp;Checkbox(复选框)

PS:另外有一点要切记,要为每个RadioButton添加一个id,不然单选功能会生效!!!

第二种方法是通过单击其他按钮获取选中单选按钮的值,当然我们也可以直接获取,这个看需求~

例子代码如下:

Button btnchange = (Button) findViewById(R.id.btnpost);
RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);
//为radioGroup设置一个监听器:setOnCheckedChanged()  
btnchange.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        for (int i = 0; i < radgroup.getChildCount(); i++) {
            RadioButton rd = (RadioButton) radgroup.getChildAt(i);
            if (rd.isChecked()) {
                Toast.makeText(getApplicationContext(), "点击提交按钮,获取你选择的是:" + rd.getText(), Toast.LENGTH_LONG).show();
                break;
            }
        }
    }
});      

运行效果图:

【Android 常见控件使用】RadioButton(单选按钮)&amp;Checkbox(复选框)

代码解析: 这里我们为提交按钮设置了一个setOnClickListener事件监听器,每次点击的话遍历一次RadioGroup判断哪个按钮被选中我们可以通过下述方法获得RadioButton的相关信息!

  • getChildCount( )获得按钮组中的单选按钮的数目;
  • getChinldAt(i):根据索引值获取我们的单选按钮
  • isChecked( ):判断按钮是否选中

第三种方法是判断被点击的id是哪一个单选按钮的id,通过id去获取值

代码如下:

// 获取组件
radioGroup = findViewById(R.id.rg);
btn_post = findViewById(R.id.btn_post);
/*
 方式三:通过判断点击的单选按钮
 */
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // 判断点击的单选按钮
        if (checkedId == R.id.radioButton1){
            RadioButton radioButton1 = findViewById(R.id.radioButton1);
            Toast.makeText(getApplicationContext(), "你选择的是:" + radioButton1.getText(), Toast.LENGTH_LONG).show();
        } else {
            RadioButton radioButton2 = findViewById(R.id.radioButton2);
            Toast.makeText(getApplicationContext(), "你选择的是:" + radioButton2.getText(), Toast.LENGTH_LONG).show();
        }
    }
});      

效果展示:

【Android 常见控件使用】RadioButton(单选按钮)&amp;Checkbox(复选框)

​​返回顶部​​

2)CheckBox(复选框)

如题复选框,即可以同时选中多个选项,至于获得选中的值,同样有三种方式:
  • 1.为每个CheckBox添加事件:setOnCheckedChangeListener;
  • 2.弄一个按钮,在点击后,对每个checkbox进行判断:isChecked();
  • 3.对选中的按钮id进行判断。

运行效果图:

【Android 常见控件使用】RadioButton(单选按钮)&amp;Checkbox(复选框)

实现代码:

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

    <TextView
        android:id="@+id/textView_head"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请选择你的爱好:"
        android:textStyle="bold"
        android:textSize="19dp"/>

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="游泳" />
    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="魔方" />
    <CheckBox
        android:id="@+id/checkBox3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="卡林巴" />
    <CheckBox
        android:id="@+id/checkBox4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="编程" />

    <TextView
        android:id="@+id/textView_end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="你选择的爱好是:"
        android:textStyle="bold"
        android:textSize="17dp"/>
</LinearLayout>      
package com.example.learning.basicItems.Button;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.example.learning.R;

public class CheckBoxActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    // 声明组件
    private CheckBox checkBox1,checkBox2,checkBox3,checkBox4;
    private TextView textView_end;
    private String hobbies;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_box);

        // 获取组件
        checkBox1 = findViewById(R.id.checkBox1);
        checkBox2 = findViewById(R.id.checkBox2);
        checkBox3 = findViewById(R.id.checkBox3);
        checkBox4 = findViewById(R.id.checkBox4);
        textView_end = findViewById(R.id.textView_end);
        hobbies = new String("你选择的爱好有:");

        // 设置事件监听
        checkBox1.setOnCheckedChangeListener(this);
        checkBox2.setOnCheckedChangeListener(this);
        checkBox3.setOnCheckedChangeListener(this);
        checkBox4.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        String hobby = buttonView.getText().toString();
        if (isChecked) {
            if (!hobbies.contains(hobby)) {
                hobbies += hobby;
                textView_end.setText(hobbies);
            }
        } else {
            if (hobbies.contains(hobby)) {
                hobbies = hobbies.replace(hobby,"");
                textView_end.setText(hobbies);
            }
        }

    }
}      

​​返回顶部​​

2.自定义点击效果

虽然5.0后的RadioButton和Checkbox都比旧版本稍微好看了点,但是对于我们来说 可能还是不喜欢或者需求,需要自己点击效果!实现起来很简单,先编写一个自定义 的selctor资源,设置选中与没选中时的切换图片~!

实现效果图如下:

【Android 常见控件使用】RadioButton(单选按钮)&amp;Checkbox(复选框)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="true"
        android:state_checked="true"
        android:drawable="@mipmap/ic_checkbox_checked"/>
    <item
        android:state_enabled="true"
        android:state_checked="false"
        android:drawable="@mipmap/ic_checkbox_normal" />
</selector>      

写好后,我们有两种方法设置,也可以说一种吧!你看看就知道了~

①android:button属性设置为上述的selctor

android:button="@drawable/rad_btn_selctor"      

②在style中定义一个属性,然后通过android style属性设置,先往style添加下述代码:

<style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">"android:button">@drawable/rad_btn_selctor</item>
</style>      

然后布局那里:

style="@style/MyCheckBox"      

​​返回顶部​​

3.改变文字与选择框的相对位置

这个实现起来也很简单,还记得我们之前学TextView的时候用到的drawableXxx吗? 要控制选择框的位置,两部即可!设置:

Step 1. android:button="@null"

Step 2. android:drawableTop="@android:drawable/btn_radio"

当然我们可以把drawableXxx替换成自己喜欢的效果!

​​返回顶部​​

4.修改文字与选择框的距离

有时,我们可能需要调节文字与选择框之间的距离,让他们看起来稍微没那么挤,我们可以:

1.在XML代码中控制: 使用android:paddingXxx = “xxx” 来控制距离

2.在Java代码中,稍微好一点,动态计算paddingLeft!

rb.setButtonDrawable(R.drawable.rad_btn_selctor);
int rb_paddingLeft = getResources().getDrawable(R.mipmap.ic_checkbox_checked).getIntrinsicWidth()+5; 
rb.setPadding(rb_paddingLeft, 0, 0, 0);