您的位置:首页 > 移动开发 > Android开发

android设置修改CheckBox框大小、颜色的两种方法

2017-07-31 19:58 549 查看
推荐第二种方法

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

首先:大小由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

需要调整颜色时直接替换图片即可,需要调整大小和位置时直接在代码里改动就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  checkbox大小改变