Search code examples
androidandroid-stylesstyleable

Get value from attribute value from XML


I have a custom class which is extened from Textview now I need to get the values in the xml for the layout. I tried

public FontTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setIncludeFontPadding(false);
    int style =  attrs.getAttributeIntValue(com.android.internal.R.styleable.TextAppearance_textStyle,-1);
    init(style);
}

but I can't get com.android.internal.R.styleable it says package don't exist. I think I can access it from out side the package.

Is there any way to get the style from xml here?

The value of styleable.TextAppearance_textStyle is -2001555 will this change or will I be able to get the correct value always by using?

int style =  attrs.getAttributeIntValue(-2001555,-1)

Solution

  • Tyr to get attribute values in this way. Pay attention to what TypedArray indices are, as described in docs.

    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    
        int[] attrsArray = new int[]{android.R.attr.textStyle};
        final TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
        int style = array.getInt(0, -1);  // returns 1 for bold, 2 for italic
        array.recycle();
    }