首先看一个错误
不写的话读取不到属性值,如下所示 error虽然编译成功,但是取不到值
ta.getDimension 的第一个参数是下标
error: No resource identifier found for attribute '' in package
这个错误主要原因是
属性不存在(注意属性区分大小写)
其中xmlns必须写,
<com.package.name.view.LinearLayoutWithLine
xmlns:app="http://schemas.android.com/apk/res-auto"
......
app:paddingLineLeft="1dip"
不写的话读取不到属性值,如下所示 error虽然编译成功,但是取不到值
<com.package.name.view.LinearLayoutWithLine
......
paddingLineLeft="1dip"
还需要注意一个问题,如果命名空间采用老式写法
<com.package.name.view.LinearLayoutWithLine
xmlns:app="http://schemas.android.com/apk/res/com.package.name"
......
app:paddingLineLeft="1dip"
xmlns最后面是res/app的包名. 而不是v自定义的iew所在的package的路径
xmlns:app="http://schemas.android.com/apk/res/com.package.name.view"
这么写是错误的
。。。。。
完整用法如下(注意查看一下顺序)
<declare-styleable name="LinearLayoutWithLine">
<!-- 线的颜色 -->
<attr name="lineColor" format="color"/>
<attr name="paddingLineLeft" format="dimension"/>
<attr name="paddingLineTop" format="dimension"/>
<attr name="paddingLineRight" format="dimension"/>
<attr name="paddingLineBottom" format="dimension"/>
</declare-styleable>
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LinearLayoutWithLine);
paddlingLineLeft = (int) ta.getDimension(R.styleable.LinearLayoutWithLine_paddingLineLeft, getPaddingLeft());
paddlingLineTop = (int) ta.getDimension(R.styleable.LinearLayoutWithLine_paddingLineTop, getPaddingTop());
paddlingLineRight = (int) ta.getDimension(R.styleable.LinearLayoutWithLine_paddingLineRight, getPaddingRight());
paddlingLineBottom = (int) ta.getDimension(R.styleable.LinearLayoutWithLine_paddingLineBottom, getPaddingBottom());
ta.recycle();
ta.getDimension 的第一个参数是下标
public static final int LinearLayoutWithLine_lineColor = 0;
public static final int LinearLayoutWithLine_paddingLineLeft = 1;
public static final int LinearLayoutWithLine_paddingLineTop = 2;
值按照declare-styleable定义的LinearLayoutWithLine中的顺序累加的
所以 取值也可以写成下列
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LinearLayoutWithLine);
paddlingLineLeft = (int) ta.getDimension(1, getPaddingLeft());
paddlingLineTop = (int) ta.getDimension(2, getPaddingTop());
paddlingLineRight = (int) ta.getDimension(3, getPaddingRight());
paddlingLineBottom = (int) ta.getDimension(4, getPaddingBottom());
ta.recycle();