Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply style only to specific TextViews

Tags:

android

xml

I have two themes that I switch back and forth between in my Android application. In some places, I have TextViews that I want to remain the default color. In other places, I want them to be another color (let's say orange). When changing themes, I'd like only the TextViews that were previously orange to become blue.

Is there a way to do this simply in Android? I had something in mind such as a class tag in html/css but can't seem to find anything.

EDIT: To clarify what I was referring to with the html/css equivalent:

<div>This text is black</div>
<div class="redDiv">This text is red</div>

.redDiv {
    color:red;
}
like image 804
Alex Vulaj Avatar asked Dec 25 '22 09:12

Alex Vulaj


1 Answers

Let's say you have two themes in your application: MyFirstTheme and MySecondTheme:

<style name="MyFirstTheme" parent="android:Theme">
    <item name="android:textViewStyle">@style/MyFirstTheme.TextView</item>
    [...]
</style>
<style name="MySecondTheme" parent="android:Theme">
    <item name="android:textViewStyle">@style/MySecondTheme.TextView</item>
    [...]
</style>

The textview styles defined in your styles.xml could look like:

<style name="MyFirstTheme.TextView" parent="@android:style/Widget.TextView">
    <item name="android:textColor">@android:color/black</item>
    [...]
</style>
<style name="MySecondTheme.TextView" parent="@android:style/Widget.TextView">
    <item name="android:textColor">@color/orange</item>
    [...]
</style>
<style name="PersistentTheme.TextView" parent="@style/MyFirstTheme.TextView">
    <item name="android:textColor">@color/red</item>
</style>

So when you have a layout with two TextViews, you can have the one completely follow the active theme by not setting anything extra to it, and you can apply other appearance to your other TextView instance by specifying a style attribute for it:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

    <!-- This textview will change text color when other style applied -->
    <TextView
        android:id="@+id/tv_styledependent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- This textview will always have the same (red) text color -->
    <TextView
        android:id="@+id/tv_persistent"
        style="@style/PersistentTheme.TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_styledependent" />

</RelativeLayout>
like image 180
rekaszeru Avatar answered Jan 05 '23 09:01

rekaszeru