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?

user4157124
  • 2,809
  • 13
  • 27
  • 42
Praveen
  • 90,477
  • 74
  • 177
  • 219

3 Answers3

25

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

Robby Pond
  • 73,164
  • 16
  • 126
  • 119
4

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

DmitryArc
  • 4,757
  • 2
  • 37
  • 42
3
setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD_ITALIC);

It works for me

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Antroid
  • 31
  • 1