android set style in code


Question

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

1
241
10/17/2016 5:36:58 AM

Accepted Answer

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);

Hope this helps.

310
3/30/2011 3:42:55 PM

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 Context


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon