自定义view 读取 属性No resource identifier found for attribute

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ID19870510/article/details/53009728
首先看一个错误
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();



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页