Home » Android » android – How to get the style attribute of a TextView

android – How to get the style attribute of a TextView

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am creating a Custom TextView class MTextView . Inside the constructor i want to know the value of style attrib of the textview so that I can set different typefaces depending on whether style is set to bold or not. But there is no getStyle() function ? What to do?

    public class MTextView extends TextView{

    public MTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            if(style.equals(TypeFace.bold))  //how to get style?
                setTypeface(Typeface.createFromAsset(getContext().getAssets(),"rc.ttf"));
    }



    }
How to&Answers:

You can get the textStyle from the TextView’s getTypeface() instance method.

int style = getTypeface().getStyle();

If no textStyle has been specified (i.e. you want to support normal textStyle) then getTypeface() can return null.

In the case where it is not null it may be best to assume textStyle is implicitly set to normal.

Answer:

Use this code:

    if (attrs != null) {
        try {
            int style = attrs.getAttributeIntValue(
                "http://schemas.android.com/apk/res/android",
                "textStyle", 
                Typeface.NORMAL);

            setTypeface(Typeface.createFromAsset(
                            getContext().getAssets(), 
                            "rc.ttf"), 
                        style);
        }
        catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }