This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Q: How do I programmatically set TextView TextStyle in Android?

Is there a way to programmatically set the textStyle property of a TextView? There seems to be no setTextStyle() method.

To be clear, I’m not talking about view/widget styles! I’m talking about the following:

<TextView
  android:id="@+id/my_text"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Hello World"
  android:textStyle="bold" />
Copy the code

Answer 1:

textview.setTypeface(Typeface.DEFAULT_BOLD);
Copy the code

If you want to keep the previous properties, you can

textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
Copy the code

Answer 2:

Suppose you have a style called RedHUGEText on values/styles.xml:

<style name="RedHUGEText" parent="@android:style/Widget.TextView">
    <item name="android:textSize">@dimen/text_size_huge</item>
    <item name="android:textColor">@color/red</item>
    <item name="android:textStyle">bold</item>
</style>
Copy the code

Simply create a TextView in the XML Layout/your_Layout. XML file as usual and say:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content android:text="FOO" />
Copy the code

Then do the following in your Activity’s Java code:

TextView textViewTitle = (TextView) findViewById(R.id.text_view_title);
textViewTitle.setTextAppearance(this, R.style.RedHUGEText);
Copy the code

It applies color, size, gravity, etc. I’ve used it on phones and tablets with An Android API level of 8 to 17 with no problems. Please note that this method has been deprecated since Android 23. The context argument is removed, so the last line needs to be:

textViewTitle.setTextAppearance(R.style.RedHUGEText);
Copy the code

To support all API levels, use androidX TextViewCompat

TextViewCompat.setTextAppearance(textViewTitle, R.style.RedHUGEText)
Copy the code

Please remember… This is only useful if the text style really depends on conditions in Java logic, or if you’re building the UI “on the fly” with code… If not, it’s best to just do:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content android:text="FOO" 
    style="@style/RedHUGEText" />
Copy the code