当我们写一个自定义控件的时候,我们需要提供很多该控件的属性供用户设置。我们可以通过开放方法的形式让用户在java代码中设置,也可以让用户通过在xml中配置来实现属性的指定。今天我就讲解一下如何让用户可以在xml中配置相关属性。
首先,我们在values文件夹中创建一个attrs.xml文件,并加入如下代码:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomPagerTab">
<attr name="textColor" format="color"/>
<attr name="textSize" format="dimension"/>
<attr name="text" format="string"/>
</declare-styleable>
</resources>
接着我们写一个自定义控件
public class MyView extends View {
private int textColor = Color.BLACK;
private float textSize = 15f;
private String text;
private Paint paint;
public MyView(Context context) {
super(context);
init(context,null);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
private void init(Context context, AttributeSet attrs){
if (attrs!=null){
//根据CustomPagerTab的属性定义,从布局文件中获取属性数组描述
TypedArray attrArray = context.obtainStyledAttributes(attrs,R.styleable.CustomPagerTab);
//根据属性描述定义,获取布局文件中的文本大小
textColor = attrArray.getColor(R.styleable.CustomPagerTab_textColor,textColor);
//根据属性描述定义,获取布局文件中的文字大小,自动转为px
textSize = attrArray.getDimension(R.styleable.CustomPagerTab_textSize,textSize);
//根据属性描述定义,获取布局文件中的文字内容
text = attrArray.getString(R.styleable.CustomPagerTab_text);
if (text == null){
text = "默认文字";
}
//回收属性数组描述
attrArray.recycle();
}
paint = new Paint();
paint.setTextSize(textSize);
paint.setColor(textColor);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(text,20,100,paint);
}
}
大家可以看到,我们在init方法中对用户设置的属性进行了一下获取,这样我们就可以实现属性的自定义。
接下来就是使用自定义控件
<com.hao.wahaha.MyView
android:layout_width="match_parent"
android:layout_height="50dp"/>
<com.hao.wahaha.MyView
android:layout_width="match_parent"
android:layout_height="200dp"
app:text="哈哈哈"
app:textColor = "@android:color/holo_blue_light"
app:textSize="20sp"
android:background="@android:color/black"/>
<com.hao.wahaha.MyView
android:layout_width="match_parent"
android:layout_height="200dp"
app:text="嘻嘻嘻"
app:textColor = "@android:color/holo_red_light"
app:textSize="40sp"
android:background="@android:color/holo_orange_dark"/>
这样我们就实现了自定义xml中可设置的属性了。之后我会继续讲解一下TypedArray中具体的类型。