attr属性的定义/读取/出错/使用

2020-08-13  本文已影响0人  安卓_背包客
a.png

*1.1 自定义attr属性与读取

/**
 * 初始化。
 *
 * @param context      上下文。
 * @param attributeSet 属性。
 */
private void initialize(Context context, AttributeSet attributeSet) {
    mPaint.setAntiAlias(true);
    TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CircleProgressbar);
    if (typedArray.hasValue(R.styleable.CircleProgressbar_circle_color)){
        inCircleColors = typedArray.getColorStateList(R.styleable.CircleProgressbar_circle_color);
    } else{
        inCircleColors = ColorStateList.valueOf(Color.TRANSPARENT);
    }
    circleColor = inCircleColors.getColorForState(getDrawableState(), Color.TRANSPARENT);
    typedArray.recycle();
}

*1.2在res/values 文件下定义一个attrs.xml 文件

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="View名称"> 
        <attr name="textColor" format="color"/> 
        <attr name="textSize" format="dimension"/>
    </declare-styleable>
</resources>

*1.3如果在attr中不同View引用相同属性名字时出现错误的解决方法
问题代码【引用代码(两个都引用了textColor会出错)】

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="View名称"> 
        <attr name="textColor" format="color"/> 
        <attr name="textSize" format="dimension"/>
    </declare-styleable>
    <declare-styleable name="View2名称"> 
        <attr name="textColor" format="color"/> 
        <attr name="hint" format="reference" />
        <attr name="inputType">
        <flag name = "text" value = "0" />
        <flag name = "number" value = "1" />
        <flag name = "textPassword" value = "2" />
        <flag name = "numberPassword" value = "3" />
        <flag name = "numberDecimal" value = "4" />
         </attr>
    </declare-styleable>
</resources>

上一篇 下一篇

猜你喜欢

热点阅读