CheckBox的创建、监听与继承

目录

简介

CheckBox是复选按钮,点击选中后再次点击可取消选中。CheckBox继承自CompoundButton(复合按钮)。使用CheckBox需要导入android.widget.CheckBoxandroid.widget.CompoundButton

CheckBox的创建

使用xml布局创建

 使用xml布局创建CheckBox的核心在于布局文件findviewById()方法。
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout...>
    ...
    <CheckBox
        android:id="@+id/cb_1"
        android:width="match_parent"
        android:height="wrap_content"
        .../>
    ...    
</LinearLayout>

MainActivity.java

import...
import android.widget.CheckBox;
import android.widget.CompoundButton

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //find a CheckBox in xml file
        CheckBox cb_1=(CheckBox)findviewById(R.id.cb_1);
        ...
    }
    ...
}

使用Java代码创建

 使用Java代码创建CheckBox的步骤与使用Java代码创建Button一致(以下均以LinearLayout为例):
 ①使用构造函数CheckBox(Context context)创建CheckBox对象

CheckBox cb_1=new CheckBox(this);

 ②为CheckBox对象设置必要属性参数

LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
         ViewGroup.LayoutParams.MATCH_PARENT,
         ViewGroup.LayoutParams.WRAP_CONTENT);
cb_1.setLayoutParams(params);         

 ③将CheckBox对象添加到目标ViewGroup

LinearLayout layout_main=(LinearLayout)findviewById(R.id.layout_main);
layout_main.addView(cb_1);

 ④在res/values/路径下创建id值资源文件并使用setId()方法为CheckBox对象设置id
res/values/cb_id.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="cb_1" type="id"/>
    ...
</resources>
cb_1.setId(R.id.cb_1);

 ⑤为CheckBox设置外观、监听器等

cb_1.setText("check1");
cb_1.setBackgroundColor(0x50ff00ff);
...
cb_1.setOnCheckedChangeListener(this);

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

layout_main.removeView(cb_1);

CheckBox的监听

 CheckBox所用的监听器为OnCheckedChangeListener,充当OnCheckedChangeListener的对象类必须实现CompoundButton.OnCheckedChangeListener接口:

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

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

public class MyCheckedChangeListener 
             implements CompoundButton.OnCheckedChangeListener {
    ...
    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
        switch(buttonView.getId()) {
            case R.id.cb_1:
                if(isChecked) {...}
                else {...}
                break;
            case R.id.cb_2:
                if(isChecked) {...}
                else {...}
                break;  
            ...      
        }           
    }
    ...
}

 每点击一次CheckBox按钮就会触发onCheckedChanged()方法。使用buttonView.getId()方法判断响应点击的CheckBox按钮;使用isChecked判断响应点击CheckBox按钮被点击后的选中状态:isCheckedtrue,响应点击的CheckBox按钮被选中;isCheckedfalse,响应点击的CheckBox按钮被弃选。

CheckBox的常用属性

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

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape android:shape="oval">
            <size
                android:width="20dp"
                android:height="20dp"/>
            <solid
                android:color="#50ff00ff"/>
            <stroke
                android:width="3dp"
                android:color="#ff000000"/>
        </shape>
    </item>
    <item android:state_checked="false">
        <shape android:shape="oval">
            <size
                android:width="20dp"
                android:height="20dp"/>
            <solid
                android:color="#ffffff"/>
            <stroke
                android:width="3dp"
                android:color="#ff000000"/>
        </shape>
    </item>
</selector>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout...>
    ...
    <CheckBox
        android:id="@+id/cb_1"
        android:width="match_parent"
        android:height="wrap_content"
        android:text="check1"
        android:background="#50005050"
        android:button="@drawable/cb_select"/>
    <CheckBox
        android:id="@+id/cb_2"
        android:width="match_parent"
        android:height="wrap_content"
        android:text="check2"
        android:background="#50505000"
        android:button="@drawable/cb_select"/>
    ...
</LinearLayout>

MainActivity.java

import...
import android.widget.CheckBox;
import android.widget.CompoundButton; 
public class MainActivity extends Activity
                       implements CompoundButton.OnCheckedChangeListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        CheckBox cb_1=(CheckBox)findviewById(R.id.cb_1);
        CheckBox cb_2=(CheckBox)findviewById(R.id.cb_2);
        cb_1.setOnCheckedChangeListener(this);
        cb_2.setOnCheckedChangeListener(this);
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
        switch(buttonView.getId()) {
            case R.id.cb_1:
                if(isChecked) {
                    Toast.makeText(this,"You select check1",Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(this,"You give up check1",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.cb_2:
                if(isChecked) {
                    Toast.makeText(this,"You select check2",Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(this,"You give up check2",Toast.LENGTH_SHORT).show();
                }
                break;   
        }
    }
}

CheckBox的继承

 自定义CheckBox时会用到CheckBox的继承。AndroidStudio要求使用AppCompatCheckBox代替CheckBox用以自定义CheckBox类的继承。对于开发者而言,自定义CheckBox中最有意义的方法是构造函数onTouchEvent()
 以下将以简单实例代码展示CheckBox继承的用法。代码实现:选中时CheckBox颜色改变并打印系统提示;弃选后CheckBox颜色恢复并打印系统提示。
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/layout_main"
    ...>
    ...
</LinearLayout>

MyCheckBox.java

import...
import androidx.appcompat.widget.AppCompatCheckBox;
public class MyCheckBox extends AppCompatCheckBox {
    //context for Toast
    private Context context;
    //constructors
    public MyCheckBox(Context context) {
        super(context);
        this.context=context;
        //use selector file for CheckBox button drawable
        this.setButtonDrawable(R.drawable.cb_select);
        this.setBackgroundColor(0x50f000f0);
    }
    public MyCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        //use selector file for CheckBox button drawable
        this.setButtonDrawable(R.drawable.cb_select);
        this.setBackgroundColor(0x50f000f0);
    }
    public MyCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context=context;
        //use selector file for CheckBox button drawable
        this.setButtonDrawable(R.drawable.cb_select);
        this.setBackgroundColor(0x50f000f0);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_DOWN) {
            Toast.makeText(context,"You pressed",Toast.LENGTH_SHORT).show();
        }
        else if(event.getAction()==MotionEvent.ACTION_UP){
            Toast.makeText(context,"You complete press",Toast.LENGTH_SHORT).show();
        }
        //must return super.onTouchEvent(event),or onCheckedChanged() method will not reach
        return super.onTouchEvent(event);
    }
}

MainActivity.java

public class MainActivity extends Activity
                       implements CompoundButton.OnCheckedChangeListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //find ViewGroup in xml file
        LinearLayout layout_main=(LinearLayout)findviewById(R.id.layout_main);
        
        //create a MyCheckBox
        MyCheckBox cb_1=new MyCheckBox(this);
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
                     ViewGroup.LayoutParams.MATCH_PARENT,
                     ViewGroup.LayoutParams.WRAP_CONTENT);
        cb_1.setLayoutParams(params);
        
        //add cb_1 to target ViewGroup
        layout_main.addView(cb_1);
        
        //set cb_1
        cb_1.setText("check1");
        //this id is in res/values/cb_id file
        cb_1.setId(R.id.cb_1);
        cb_1.setOnCheckedChangeListener(this);                             
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
        if(buttonView.getId==R.id.cb_1) {
            if(isChecked) {
                Toast.makeText(this,"You select check1",Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(this,"You give up check1",Toast.LENGTH_SHORT).show();
            }
        }
    }
}

欢迎指正
上一篇:006、py43-day06-sky-20210805_2


下一篇:Python yield与实现