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
The accepted answer was great solution for me. The only thing to add is about
inflate()
method.In accepted answer all
android:layout_*
parameters will not be applied.The reason is no way to adjust it, cause
null
was passed asViewGroup parent
.You can use it like this:
View view = inflater.inflate(R.layout.view, parent, false);
and the
parent
is theViewGroup
, from where you like to adjustandroid:layout_*
.In this case, all relative properties will be set.
Hope it'll be useful for someone.
I do not believe you can set the style programatically. To get around this you can create a template layout xml file with the style assigned, for example in res/layout create tvtemplate.xml as with the following content:
then inflate this to instantiate your new TextView:
Hope this helps.
I met the problem too, and I found the way to set style programatically. Maybe you all need it, So I update there.
The third param of View constructor accepts a type of attr in your theme as the source code below:
So you must pass a type of R.attr.** rather than R.style.**
In my codes, I did following steps:
First, customize a customized attr to be used by themes in attr.xml.
Second, specific your style in your used theme in style.xml.
At the end, use it!
the view created programatically will use the specified style in your theme.
You can have a try, and hope it can work for you perfectly.
Dynamically changing styles is not supported (yet). You have to set the style before the view gets created, via XML.