I'm trying to use the TextView constructor with style like this:
TextView myText = new TextView(MyActivity.this, null, R.style.my_style );
however, when i do this, the text view does not appear to take the style (I verified the style by setting it on a static object).
I've also tried using myText.setTextAppearance(MyActivity.this, R.style.my_style)
but it also doesn't work
You can create a generic style and re-use it on multiple textviews like the one below:
Edit: this refers to Context
You can pass a ContextThemeWrapper to the constructor like this:
I have only tested with EditText but you can use the method
to apply a style defined in an XML file.
Sine this method belongs to View I believe it will work with any UI element.
regards.
When using custom views that may use style inheritance (or event styleable attributes), you have to modify the second constructor in order not to lose the style. This worked for me, without needing to use setTextAppearence():
Parameter int
defStyleAttr
does not specifies the style. From the Android documentation:To setup the style in View constructor we have 2 possible solutions:
With use of ContextThemeWrapper:
With four-argument constructor (available starting from LOLLIPOP):
Key thing for both solutions -
defStyleAttr
parameter should be 0 to apply our style to the view.You can set the style in the constructor (but styles can not be dynamically changed/set).
View(Context, AttributeSet, int)
(theint
is a style resource)Answer from Romain Guy
reference