Search code examples
androidtextviewandroid-resources

Android set background color to TextView in styles.xml


In my application, I want to set a style to the TextView which will make the TextView look like a header as shown in the following figure-

"General" is the heading in this image.

When I apply the style from the styles.xml (given below), it applies the font and font color as specified. But, it does not apply the white background. Can we at all do this?

The style defined is like this-

<?xml version="1.0" encoding="utf-8"?>

<style name="settings_header">
    <item name="android:layout_marginBottom"> 10dip </item>
    <item name="android:background"> @color/white </item>
    <item name="android:paddingLeft"> 10dip </item>
    <item name="android:layout_width"> match_parent </item>
    <item name="android:layout_height"> wrap_content </item>
    <item name="android:textSize"> 22sp </item>
    <item name="android:textColor"> @color/black </item>
    <item name="android:textStyle"> bold </item>
</style>

The code which applies the style is like

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textView);
textview.setTextAppearance(ScrSettings.this,R.style.settings_header);
}

Solution

  • As a workaround, this works

    textview.setTextAppearance(context, R.style.settings_header);
    textview.setBackgroundResource(R.color.white);
    

    The question is still not answered fully as, setting the background to the TextView twice is not what we want. We had already set the background in styles.xml.