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一致(詳見Button的創建、監聽與繼承):
 ①使用構造函數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();
            }
        }
    }
}

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