Brahadeesh
Brahadeesh

Reputation: 2255

setting style for textview in code, android

I have the following code in my activity:

......  
DataCell[i] = new TextView(context,null,R.style.TitleRow);
DataCell[i].setText(data[i]);
......

Here is my style.xml file, which is in res >> values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="TitleRow" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#A0A0A0</item>
        <item name="android:layout_marginTop">5dp</item>
        <item name="android:layout_marginBottom">5dp</item>
        <item name="android:paddingLeft">2dp</item>
        <item name="android:paddingRight">2dp</item>
    </style>
</resources>

No value is getting displayed.. But if I use DataCell[i] = new TextView(context) , its working fine. I know there is some problem with the fact that I am using null for attribute set. But after searching for a long time I am unable to find a perfect example of how to do it. I hope someone could clarify this to me once and for all.

Upvotes: 1

Views: 7693

Answers (2)

P.Melch
P.Melch

Reputation: 8180

I usually end up creating a simple layout file only containing the element I want to instantiate ( TextView in your case ) that has the proper style applied and use the layout inflater to create the instance for me.

layout file: styled_textview.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView ... style="@+style/MyStyle" ... />

code:

activity.getLayoutInflater().inflate(R.layout.styled_textview, <root_node>, true);

Upvotes: 2

nostra13
nostra13

Reputation: 12407

Try to inflate your TextView. Like this:

layout/cell_row.xml

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/TitleRow">

YourActivity.java

......  
LayoutInflater inflater = getLayoutInflater(); // called from activity
......
DataCell[i] = inflater.inflate(R.layout.cell_row, null); 
// or inflater.inflate(R.layout.cell_row, root, false);   where root is a parent view for created TexView 
DataCell[i].setText(data[i]);
......

Upvotes: 3

Related Questions