1

I'd like to add more than one theme for an app, selectable programmatically.

How can I define a style for a specific view inside those themes?

Let's say I have an ImageView that show a logo in my_layout.xml:

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

    <ImageView 
        android:layout_width="250dp"
        android:layout_height="250dp"

        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"

        android:src="@drawable/ic_logo"
        android:contentDescription="@string/app_name"
        />
    <!-- ...other views... -->
</RelativeLayout>

How can I change the src of the ImageView changing the Theme?

Is there a way to define custom elements for a theme so that I can then apply to a specific view?

Something like:

<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="MyTheme" parent="android:Theme.Holo.Light">
        <item name="logoImageView">@style/baseLogoImageView</item>
    </style>

    <style name="baseLogoImageView">
        <item name="android:src">@drawable/ic_logo</item>
    </style>

</resources>

and then use it in my_layout.xml:

...
<ImageView style="@style/logoImageView"
...

The above example didn't work; I'm missing something or it isn't possible to achieve that result?

Thanks in advance.

Ohmnibus
  • 415
  • 6
  • 18

1 Answers1

1

I found a solution myself based on this answer:

Declare attribute to use as style reference:

<declare-styleable name="CustomThemeViews">
    <attr name="myViewStyle" format="reference"/>
</declare-styleable>

Define styles for each theme:

<style name="myViewStyleTheme01">
    <item name="android:background">#f00</item>
</style>

<style name="myViewStyleTheme02">
    <item name="android:background">#0f0</item>
</style>

Define themes that refer to different styles:

<style name="AppTheme" parent="android:Theme.Light">
    <item name="myViewStyle">@style/myViewStyleTheme01</item>
</style>

<style name="AppThemeAlternative" parent="android:Theme.Light">
    <item name="myViewStyle">@style/myViewStyleTheme02</item>
</style>

Use themed styles in layout

<ListView style="?attr/myViewStyle"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ...

Now the style applied to the ListView changes according to the theme applied.

Community
  • 1
  • 1
Ohmnibus
  • 415
  • 6
  • 18