抽了点时间,看了一下自定义view,打算学习一下这方面的知识。都说这是Android进阶的必经之路。想要进阶的话,那自然是免不了了。
本篇学一下xml中自定义属性来控制view的效果。
第一步:
res/values文件夹下新建attrs.xml文件,里面声明自定义view时,可以在xml里用到的属性。这里以一个文本间隔属性为例来说明,当然,可以添加多个属性。
例如:文字间距,声明如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="styleAttr">
<attr name="textSpacing" format="float"/>
</declare-styleable>
</resources>
这个textSpacing到时就是可以在xml中使用的自定义的属性。
例如:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.szh.demo.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:textSpacing="1" />
</LinearLayout>
这里面要注意添加命名空间。
第二步:继承View,获取属性并使用属性。
代码如下:
public class MyView extends View {
private Paint paint;
private float textSpacing;//字体间距
public MyView(Context context) {
this(context, null);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//获取属性值
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.styleAtt);
textSpacing = array.getFloat(R.styleable.styleAttr_textSpacing, 0);
array.recycle();
init();
}
private void init() {
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setTextSize(30);
//拿到属性值,自定义效果时可直接拿来用
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
paint.setLetterSpacing(textSpacing);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("镜花水月", 0, 30, paint);
}
}