Is there a way to set the textStyle
attribute of a TextView
programmatically? There doesn\'t appear to be a setTextStyle()
method.
Let's say you have a style called RedHUGEText on your values/styles.xml:
Just create your TextView as usual in the XML layout/your_layout.xml file, let's say:
And in the java code of your Activity you do this:
TextView textViewTitle = (TextView) findViewById(R.id.text_view_title);
textViewTitle.setTextAppearance(this, R.style.RedHUGEText);
It worked for me! And it applied color, size, gravity, etc. I've used it on handsets and tablets with Android API Levels from 8 to 17 with no problems. Note that as of Android 23, that method has been deprecated. The context argument has been dropped, so the last line would need to be:
textViewTitle.setTextAppearance(R.style.RedHUGEText);
Remember... this is useful only if the style of the text really depends on a condition on your Java logic or you are building the UI "on the fly" with code... if it doesn't, it is better to just do:
You can always have it your way!