How do I set the style of a textView programmatically?

Solution:

You can't programmatically set the style of a View, but you might be able to do something like textView.setTextAppearance(context, android.R.style.TextAppearance_Small);.


It is not currently possible to set the style of a View 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:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is a template"
        style="@android:style/TextAppearance.DeviceDefault.Small" />

then inflate this to instantiate your new TextView:

TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);

Actually, this is possible as of API level 21.

TextView has a 4 parameter constructor:

TextView (Context context, 
          AttributeSet attrs, 
          int defStyleAttr, 
          int defStyleRes)

The middle two parameters are not necessary in this case. The following code creates a TextView directly in an activity and only defines its style resource:

TextView myStyledTextView = new TextView(this, null, 0, R.style.my_style);