饭后Android 第二餐-复选框CheckBox+开关按钮Switch+单选按钮RadioButton

饭后Android 第一餐-导航视图NavigationView+抽屉布局DrawerLayout+工具栏Toolbar

1.CompoundButton概述

在Android中,CompoundButton类是抽象类的复合按钮,因为是抽象类,所以不能直接使用,实际开发中用的是
CompoundButton类的几个派生类,主要有复选框,开关按钮Switch和单选按钮RadioButton,这些派生类都可使用CompoundButton的属性和方法

CompoundButton 布局文件属性

  • android:checked : 指定按钮的勾选状态,ture表示勾选,flase表示未勾选,默认为未勾选
  • android:button:指定左侧勾选图标的图形,如果不指定就使用系统默认的图标

CompoundButton 在逻辑代码中可以使用下列四种方法进行设置

  • setChecked:设置按钮的勾选状态
  • setButtonDrawable:设置左侧勾选图标的图形
  • setOnCheckedChangeListener:设置勾选状态的监听器
  • isChecked:判断按钮是否勾选

1.复选框CheckBox

复选框CheckBox是CompoundButton 一个最简单的实现,点击复选框勾选,再次点击取消勾选,CheckBox通过
setOnCheckedChangeListener方法实现监听器,对应的监听器要实现接口CompoundButton .setOnCheckedChangeListener.

1.UI布局

把四个复选框嵌套到了一个约束布局里面,然后用了一个自定义按钮图形

在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请选择你的课程"
        android:textColor="#000000"
        android:textSize="24dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />



        app:layout_constraintTop_toBottomOf="@id/check_3" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/con"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/textView">

        <CheckBox
            android:id="@+id/check_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Android"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="@id/con" />

        <CheckBox
            android:id="@+id/check_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="JAVA"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@id/check_1" />

        <CheckBox
            android:id="@+id/check_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="C语言"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@id/check_2" />

        <CheckBox
            android:id="@+id/check_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="算法"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@id/check_3" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提交"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/check_5" />

    <CheckBox
        android:id="@+id/check_5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="确认"
        android:button="@drawable/button_style"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/con" />


</androidx.constraintlayout.widget.ConstraintLayout>

按钮样式代码 ---------button_style

<?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/a2"/>
    <item android:drawable="@drawable/a1"/>


</selector>

2按钮监听


public class MainActivity extends AppCompatActivity {
    
    

    ConstraintLayout mConstraintLayout;
    Button mButton;
    CheckBox mCheckBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton=findViewById(R.id.button);
        mConstraintLayout=findViewById(R.id.con);
        mCheckBox=findViewById(R.id.check_5);



        mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    
    //设置监听器
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    
    
                if(isChecked){
    
    
                    Toast.makeText(MainActivity.this, "确认成功", Toast.LENGTH_SHORT).show();

                }else{
    
    
                    Toast.makeText(MainActivity.this,"请确认选择", Toast.LENGTH_SHORT).show();
                }

            }
        });

        mButton.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    


                if (mCheckBox.isChecked()) {
    
    
                    StringBuffer stringBuffer=new StringBuffer();//StringBuffer本质上是一个字符数组
                    int Num = mConstraintLayout.getChildCount();  //拿到所有的子类长度
                    for (int i = 0; i < Num; i++) {
    
    
                        //根据i 拿到每一个CheckBox
                        CheckBox checkBox= (CheckBox) mConstraintLayout.getChildAt(i);
                        if(checkBox.isChecked()){
    
     //判断CheckBox是否被选中
                            //把被选中的文字添加到StringBuffer中
                            stringBuffer.append(checkBox.getText().toString()+" ");
                        }
                    }

                    Toast.makeText(MainActivity.this, "成功选择课程"+stringBuffer.toString(), Toast.LENGTH_SHORT).show();
                }else {
    
    
                    Toast.makeText(MainActivity.this,"请确认选择",Toast.LENGTH_SHORT).show();
                }


            }
        });






    }

补充一:
设置 确认 复选框的监听器,通过实现接口CompoundButton.OnCheckedChangeListener来对复选框进行监听,再通过判断是否被选中来“吐丝”
在这里插入图片描述
补充二:
在 提交 按钮的点击事件里,首先先判断 确认 按钮是否被选中,如果没被选中,就会打印请确认选择,如果被选中,就会新建了一个StringBuffer字符数组,用来存复选框中的文字内容,然后再拿到之前约束布局里嵌套的子类数量,通过for循环来判断子类中的复选框是否被选中,并且将选中的目标内容存进字符数组,在for循环结束后通过toast 打印在屏幕上
在这里插入图片描述
运行
在这里插入图片描述

2.开关按钮Switch

Switch是开关按钮,Android从4.0版本开始支持该控件,其实Switch是一个高级版本的CheckBox,在选中与取消选中时可展现的界面元素比CheckedBox丰富,

1.UI布局

方法一:通过xml来设置
Switch新添加的xml属性

xml中的属性 说明
textOn 设置右侧开启时的文本
textOff 设置左侧关闭时的文本
switchPadding 设置左右两个开关按钮之间的距离
thumbTextPadding 设置文本左右两边的距离,如果设置了该属性,switchPadding属性就会失效
thumb 设置开关轨道的背景
track 设置开关标识的图标

在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">


    <Switch
        android:id="@+id/switc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:thumbTextPadding="10dp"
        android:showText="true"
        android:textOff="@string/textOff"
        android:textOn="@string/textOn"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" />




</androidx.constraintlayout.widget.ConstraintLayout>

方法二:通过java代码来设置

Switch类的设置方法 说明
setTextOn 设置右侧开启时的文本
setTextOff 设置左侧关闭时的文本
setSwitchPadding 设置左右两个开关按钮之间的距离
setThumbTextPadding 设置文本左右两边的距离,如果设置了该属性,switchPadding属性就会失效
thumb 设置开关轨道的背景
track 设置开关标识的图标

java代码


public class MainActivity extends AppCompatActivity {
    
    

    Switch mSwitch;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSwitch=findViewById(R.id.switc);
        mSwitch.setShowText(true);
        mSwitch.setTextOn(" 打开" );
        mSwitch.setTextOff(" 关闭" );
        mSwitch.setThumbTextPadding(15);

    }
}

在这里插入图片描述

xml代码(可以看到xml没有设置属性的代码)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">


<Switch
    android:id="@+id/switc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintStart_toStartOf="parent" />



</androidx.constraintlayout.widget.ConstraintLayout>

2.按钮监听

在这里插入图片描述

public class MainActivity extends AppCompatActivity {
    
    

    Switch mSwitch;
    TextView mTextView;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSwitch=findViewById(R.id.switc);
        mTextView=findViewById(R.id.text);
        mTextView.setText("开关状态为关");


        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    
    
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    
    
                if (mSwitch.isChecked()) {
    
    

                    mTextView.setText("开关状态为开");

                }else {
    
    
                    mTextView.setText("开关状态为关");
                }
            }
        });




    }
}

运行
在这里插入图片描述

3.单选按钮RadioButton

单选按钮要在一组中选择其中一项,并且不能多选,这要求有个容器确定这组按钮的范围,这个容器便是RadioGroup,RadioGroup实质上是个布局,同一组RadioButton都要放在同一个RadioGroup节点下,RadioGroup有orientation属性可指定下级控件的排列方向,该属性为horizontal时,单选按钮在水平方向排列,该属性为vertical时,单选按钮在垂直方向排列,RadioGroup下面除了RadioButton,还可以挂载其他子控件(如TextView,ImageView等)这样看来,RadioGroup就是一个特殊的线性布局,只不过多了管理单选按钮的功能

1.UI布局

在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">


   <RadioGroup
       android:id="@+id/radiogroup"
       android:layout_width="match_parent"
       app:layout_constraintTop_toTopOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       android:layout_height="wrap_content">
       <TextView
           android:id="@+id/text"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:gravity="center"
           android:textColor="#000000"
           android:text="请选择一项你喜欢的体育项目"/>

       <RadioButton
           android:id="@+id/radiobutton1"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="篮球"/>
       <RadioButton
           android:id="@+id/radiobutton2"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="游泳"/>
       <RadioButton
           android:id="@+id/radiobutton3"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="跑步"/>
       <RadioButton
           android:id="@+id/radiobutton4"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="羽毛球"/>



   </RadioGroup>





</androidx.constraintlayout.widget.ConstraintLayout>

2.按钮监听

RadioGroup 代码中常用的3个方法

  • check:选中指定资源编号的单选按钮
  • getCheckRadioButton:获取选中状态单选按钮的资源编号
  • setOnCheckedChangeListener:设置单选按钮勾选变化的监听器

RadioButton默认未选中,点击后显示选中,但是再次点击不会取消选中,只有点击同组的其他单选按钮时,原来的单选按钮才会取消选中,另外,单选按钮的选中事件一般不由RadioButton处理,而是由RadioGroup响应,选中事件在实现时,首先要写一个单选监听器实现接口RadioGroup。OnCheckedChangeListenter,然后调用RadioGroup对象的 setOnCheckChangeListener方法注册该监听器。

在这里插入图片描述


public class MainActivity extends AppCompatActivity {
    
    

    RadioGroup mRadioGroup;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       mRadioGroup=findViewById(R.id.radiogroup);



        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    
    
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
    
    //在用户点击组内的单选按钮时触发
                RadioButton radioButton=findViewById(checkedId);
                String string=radioButton.getText().toString();
                Toast.makeText(MainActivity.this,"成功选择"+string,Toast.LENGTH_SHORT).show();
            }
        });





    }
}

运行
在这里插入图片描述

ok 以上就是本餐的饭后甜点啦,希望小伙伴们可以好好品尝。谢谢您的阅读

想不到有朝一日我在生日这一天还在学习,我觉得这样真的挺好的,今天是20岁的第一天,我想我的人生就从今天开始就要迈向更高的位置吧,为了让自己和家人过上更好的生活,也为了自己的理想,加油。20岁的ROSE J,火力全开
博主为了可以学到更多的Android知识,创建了一个安卓知识交流群,欢迎大佬入群,当然也欢迎和我一样的安卓小白,我们可以一起交流,最重要的是快乐水群,记得定个小目标,冲击bat

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_46526828/article/details/108032484