前言
前段时间封装过一个控件,效果如下图所示:
使用者只需传入button的数据即可实现效果。因为按钮的样式都是用xml文件实现的,因此颜色也是指定好的。后来想着别人要使用你的控件,颜色肯定需要和他们自己的应用搭配,所以如果要做好就需要提供一个属性,可以让使用者指定控件的主要颜色。可是我不知道要如何在代码中动态改变drawable文件中指定的颜色,那时候还问过一位技术人员,是否可以在代码里动态改变xml文件中的颜色,那时他说不行,要多个颜色就写多个xml文件,但我想着应该是可以的吧,要不然别人封装的控件就只能有一个颜色吗?后来果然查到有一种方法可以实现效果,可见还是要自己实践一下才知道行不行,因此记录一下。
参考方法地址:http://www.jianshu.com/p/5353745f07db
正文
为了定义一个自定义控件的属性,我在values文件夹下建立一个attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TabButtonRecyclerView">
<attr name="mainColor" format="color" />
</declare-styleable>
</resources>
并在自定义View的构造方法中获取该属性
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TabButtonRecyclerView, defStyle, 0);
// 默认color.xml中定义的mainColor
mainColor = typedArray.getColor(R.styleable.TabButtonRecyclerView_mainColor, getResources().getColor(R.color.mainColor));
因为不是每一个按钮的样式都是一样的,比如说两边的按钮是有圆角的,因此我没有用selector选择器来实现点击切换样式的效果,而是在代码里控制切换,故关键代码就写在切换效果的地方。
比如其中一个drawable下的xml文件如下,是一个shape元素:
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners
android:bottomLeftRadius="6dp"
android:topLeftRadius="6dp"/>
<solid android:color="@color/mainColor" />
</shape>
所以修改颜色的代码如下:
holder.tvButtonText.setBackgroundResource(R.drawable.shape_left_select);
// shape_left_select.xml里是一个shape元素,设置该元素的颜色为用户指定的颜色
GradientDrawable drawable =(GradientDrawable)holder.tvButtonText.getBackground();
drawable.setColor(mainColor);
如果修改的是边框的颜色,则需要写drawable.setStroke(2, mainColor);
其他都是用类似的方式改变颜色,但其中遇到了一个特殊的情况,比如说xml文件不是一个shape元素,而是一个layer-list元素,上面的两行代码就会报错了
例如一个xml文件如下:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 连框颜色值 -->
<item>
<shape>
<solid android:color="@color/mainColor" />
</shape>
</item>
<!-- 主体背景颜色值 -->
<item
android:bottom="1dp"
android:top="1dp"
android:left="1dp">
<shape>
<solid android:color="@color/white" />
</shape>
</item>
</layer-list>
那么就需要以下的代码进行修改了:
holder.tvButtonText.setBackgroundResource(R.drawable.shape_middle);
// 此处使用的是LayerDrawable,是因为shape_middle.xml内定义的是一个layer-list元素
// layer-list是将多个图片或shape、selector等种效果按照顺序层叠起来,每一个是用item包裹起来
// 而shape_middle.xml包含一个边框shape和一个内容shape
// 又因是未选择状态,内容为白色,边框为主色调,故先取出第一个元素(表示边框的shape),设置颜色为主色调
LayerDrawable layerDrawable = (LayerDrawable) holder.tvButtonText.getBackground();
GradientDrawable drawable = (GradientDrawable)layerDrawable.getDrawable(0);
drawable.setColor(mainColor);
这样在使用的时候指定颜色属性就可以实现属于自己的控件效果了,要使用自定义属性还需要加上一句:
xmlns:app=“http://schemas.android.com/apk/res-auto”
<com.shirley.android.tabbutton.TabButtonRecyclerView
android:id="@+id/tab_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:listitem="@layout/item_tab_button"
app:mainColor="#F08080">
</com.shirley.android.tabbutton.TabButtonRecyclerView>
效果
如有错误,望大神指出,非常感谢!
----------------------------------------时隔一年的分割线-------------------------------
这个当时的记录文档,前些日子在项目中用到过这个控件,