how to set the Style Attribute Programmatically in Android?
Asked Answered
G

3

11

I have to set the style for a TextView which is created programmatically.

How do I implement style="@style/test" programmatically?

I have looked at the Android developer style documentation already, but it did not answer my question. Any ideas?

Gammon answered 14/7, 2010 at 13:15 Comment(2)
you can refer to this answer on stack overflow https://mcmap.net/q/102750/-set-the-layout-weight-of-a-textview-programmaticallyVouge
Is this supported now ?Alkali
A
25

Dynamic style change is not currently supported. You must set the style before the view is create (in xml).

Alexia answered 14/7, 2010 at 13:17 Comment(2)
what class i have to use for that?Gammon
You just put style="@style/test" in the definition for your TextView in the layout xml file.Alexia
I
5

You can pass the style to view's constructor. This can be done in 2 ways:

  1. Use ContextThemeWrapper and setup your style as a Theme for it:

    ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.test);
    TextView testView = new TextView(wrappedContext, null, 0);
    

And important note here - to properly set the style with ContextThemeWrapper we have to use three-argument constructor and set defStyleAttr parameter to 0. Otherwise the default button style will be applied to the view.

  1. Starting from API 21 we can use constructor with 4 parameters:

    View (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
    

Where defStyleRes is your style ID

With the same remark - defStyleAttr should be 0

Idealistic answered 5/2, 2017 at 15:27 Comment(0)
A
3
setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD_ITALIC);

It works for me

Abstriction answered 30/1, 2013 at 13:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.