How we add styles programmatically?

2019-01-29 01:01发布

问题:

I have written one style for TextView and I set that one for my TextView as style="@style/popup_window_text_style" working fine, no issues.

Now I want that same style to do in programmatically for my textview

TextView textView = new TextView(mContext);

Is there any way to do it programmatically in Java?

My style in styles.xml

<style name="popup_window_text_style">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:minWidth">60dp</item>
        <item name="android:padding">10dp</item>
        <item name="android:layout_marginLeft">1dp</item>
        <item name="android:layout_marginRight">1dp</item>
        <item name="android:background">@drawable/ctxmenu_btn_selector</item>
        <item name="android:textColor">@android:color/black</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">16sp</item>
        <item name="android:gravity">center_vertical</item>
        <item name="android:singleLine">true</item>
    </style>

回答1:

This should work for you:

textView.setTextAppearance(getApplicationContext(), R.style.popup_window_text_style);

But note that some properties may not be affected and may have to be set manually as specified in the Android developer docs.

Unfortunately the current SDK appears to lack any form of a setStyle() method.