本文讲述如何在布局文件中添加原本所不具备的属性,以PagerTabStrip控件为例,增加textColor与textSize属性。
一、属性声明
新建res/values下的attrs.xml文件(文件名自取),在resources中增加declare-styleable,attr节点即扩展的属性。
declare-styleable:其name属性值为所修改的控件名;
attr:其name属性为添加的属性名,其format属性为新属性的数据类型。
<resources>
<declare-styleable name="myPagerTab">
<attr name="android:textColor" format="color"/>
<attr name="android:textSize" format="dimension"/>
</declare-styleable>
</resources>
二、构造对象
新建类myPagerTab继承自PagerTabStrip
2.1 重写构造函数:构造函数一般需要重写三种,分别是:
public myPagerTab(Context context)//在声明对象时采用
public myPagerTab(Context context, AttributeSet attrs)//布局文件中引用时采用
public myPagerTab(Context context,AttributeSet attrs,int def)//在代码中指定默认风格,其中第三个参数时参照类型(reference),使用方式参照《AS开发实战》P192。
2.2 重写测量函数:onMeasure,非必须,仅在复杂视图中重写
2.3 重写绘图函数:在onLayout、onDraw、dispatchDraw中视情况重写一个至多个
private int textColor = Color.BLUE;
private int textSize = 30;
@Override
protected void onDraw(Canvas canvas) { // 绘制函数
setTextColor(textColor); // 设置标题文字的文本颜色
setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize); // 设置标题文字的文本大小
super.onDraw(canvas);
}
2.4 实现的myPagerTab控件文本效果
![ab0ddde9a342348da86c46cf37cd22cb.png](https://i-blog.csdnimg.cn/blog_migrate/161371a0b936de9d7c16e882fdd0c9b6.png)