在java中获取attr的值

首先说如何获取已经在style里面定义好的attr的值,以colorPrimary为例:

TypedValue value = new TypedValue();
        mContext.getTheme().resolveAttribute(R.attr.colorPrimary,value,true);

value.data里面存储着的就是获取到的colorPrimary的值了。

其二,说一说如何获取自定义属性的值,这个在网上都传烂了,随便找段代码来贴上吧:

public MyView(Context context,AttributeSet attrs)     
    {     
        super(context,attrs);     
        mPaint = new Paint();     
             
        TypedArray a = context.obtainStyledAttributes(attrs,     
                R.styleable.MyView);     
             
        int textColor = a.getColor(R.styleable.MyView_textColor,     
                0XFFFFFFFF);     
        float textSize = a.getDimension(R.styleable.MyView_textSize, 36);     
             
        mPaint.setTextSize(textSize);     
        mPaint.setColor(textColor);     
             
        a.recycle();     
    } 
原文地址:https://www.cnblogs.com/DarkMaster/p/4586268.html