android設置修改CheckBox框大小、顏色的兩種方法

推薦第二種方法

-------------------------------------------------

首先:大小由Java代碼來設置;顏色由圖片來決定;

注意:如果有人的checkbox太大或太小,應該是選擇的drawable文件夾不對,我這個是大尺寸的,放在了drawable-xxhdpi下。如果你用自己的圖片,請根據美工做圖的大小來放到相應的drawable下。

準備:兩張用作CheckBox選中和沒有選中狀態的圖片到res的drawable-xxhdpi中,名稱可以設置如下:

checkbox_checked.png

checkbox_normal.png

【第一種簡單的方法:】

1、在res/drawable-xxhdpi中添加checkbox_style.xml,用於定義checkbox的drawable圖片。
 
 1
 2
 3
 4
 5
 6
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checkbox_checked" android:state_checked="true" />
<item android:drawable="@drawable/checkbox_normal" android:state_checked="false" />
<item android:drawable="@drawable/checkbox_normal"/>
</selector>
 來自CODE的代碼片
checkbox_style.xml

2、在values文件夾下的styles.xml文件中添加MyCheckBox樣式

 1
 2
 3
<style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:button">@drawable/checkbox_style</item>
</style>
 來自CODE的代碼片
styles.xml

3、在layout佈局文件中使用MyCheckBox樣式

 1
 2
 3
 4
 5
<CheckBox
android:id="@+id/select_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/MyCheckBox" />
 來自CODE的代碼片
activity_main.xml


【第二種稍微複雜的方法:】

注:關鍵點在於設置

android:button="@null"

以及

drawable.setBounds(0,0,40,40);
checkBox.setCompoundDrawables(drawable,null,null,null);


二、在res/drawable-xxhdpi中添加checkbox_style.xml,用於定義checkbox的drawable圖片。
 
 1
 2
 3
 4
 5
 6
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checkbox_checked" android:state_checked="true" />
<item android:drawable="@drawable/checkbox_normal" android:state_checked="false" />
<item android:drawable="@drawable/checkbox_normal"/>
</selector>
 來自CODE的代碼片
checkbox_style.xml

三、在Layout中修改checkbox的屬性,注意android:button="@null"是自定義的關鍵。

 1
 2
 3
 4
 5
 6
 7
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@null"
android:text="選擇框文字"
android:textSize="15sp" />
 來自CODE的代碼片
activity_main.xml

四、在Activity中的Java代碼中設置大小和位置

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
//取得CheckBox對象
CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
//取得設置好的drawable對象
Drawable drawable = this.getResources().getDrawable(R.drawable.checkbox_style);
//設置drawable對象的大小
drawable.setBounds(0,0,40,40);
//設置CheckBox對象的位置,對應爲左、上、右、下
checkBox.setCompoundDrawables(drawable,null,null,null);
 來自CODE的代碼片
MainActivity.java

需要調整顏色時直接替換圖片即可,需要調整大小和位置時直接在代碼裏改動就可以了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章