Skip to content Skip to sidebar Skip to footer

Theme A Single Textview Background Color In Styles.xml

I have an application that has multiple themes. I have a single TextView who's background needs to change color with each theme, all other TextView's stay their default theme. I cr

Solution 1:

I found a way where you can set a different background color for a specific TextView. Also, you will be able to set it according to each theme that you have.

Answer :

Creating your own attribute custom attribute in attr.xml

Below is the implementation:

Step 1

First, create a attr.xml file at your res/values folder and insert following content:

res/values/attr.xml

<?xml version="1.0" encoding="utf-8"?><resources><attrname="customTextViewBackAttributeColor"format="color" /></resources>

Step 2

That attribute that you created should be set with a Color in every theme that you have as below:

styles.xml

<resources><stylename="AppTheme.Blue"parent="Theme.AppCompat.NoActionBar"><!-- Specific Text View Color --><itemname="customTextViewBackAttributeColor">@color/color_for_theme_blue</item></style><stylename="AppTheme.Red"parent="Theme.AppCompat.Light.NoActionBar"><!-- Specific Text View Color --><itemname="customTextViewBackAttributeColor">@color/color_for_theme_red</item></style></resources>

Step 3

Finally, set that attribute as the background color of your custom view.

Note

You can set this color as background of your specific TextView. This way, only that TextView will have a different background color (and not the default background color defined in each theme). This way, you don't need to create a CustomView only to have a different Background Color.

res/layout/activity_layout.xml

<com.pivoto.gui.generic.CustomHeaderTextViewandroid:layout_width="250dp"android:layout_height="40dp"android:text="Hello World!"android:background="?customTextViewBackAttributeColor"/><TextViewandroid:layout_width="250dp"android:layout_height="40dp"android:text="Hello World2!"android:background="?customTextViewBackAttributeColor"/><TextViewandroid:layout_width="250dp"android:layout_height="40dp"android:text="Hello World3!"android:background="?customTextViewBackAttributeColor"/>

Post a Comment for "Theme A Single Textview Background Color In Styles.xml"