Set style for TextView programmatically

You can create a generic style and re-use it on multiple textviews like the one below:

textView.setTextAppearance(this, R.style.MyTextStyle);

Edit: this refers to the Context object.


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:

<?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="@style/my_style" />

then inflate this to instantiate your new TextView:

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

You can pass a ContextThemeWrapper to the constructor like this:

TextView myText = new TextView(new ContextThemeWrapper(MyActivity.this, R.style.my_style));