Nimesh Madhavan
Nimesh Madhavan

Reputation: 6318

Android app: Switch images based on theme from code

I am trying to show a favorite button which as two states (pressed/not pressed). I have 2 sets of images I want to use depending up on the theme selected (Light/Dark).

Although i am able to switch the image based on theme I am not sure how to get the Url to the image from the code so that I can show the image according to the button state. I tried using Selectors too, but I don't seem to be able to put ?attr values in selector to switch images by theme.

Style definition:

<attr name="star_on_image" format="reference"/>
<attr name="star_off_image" format="reference"/>

<style name="LightTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="star_on_image">@drawable/ic_action_important</item>
    <item name="star_off_image">@drawable/ic_action_not_important</item>
</style>

<style name="DarkTheme" parent="Theme.AppCompat">
    <item name="star_on_image">@drawable/ic_action_dark_important</item>
    <item name="star_off_image">@drawable/ic_action_dark_not_important</item>
</style>

Button Definition:

<ImageButton
            android:layout_width="@dimen/button_size"
            android:layout_height="@dimen/button_size"
            android:id="@+id/favorite_button_on"
            android:src="?attr/star_off_image"
            android:scaleType="center"
            android:visibility="gone"
            />

I want to switch this image's src attribute to "?attr/star_on_image" from code. Any ideas on how to do this?

Upvotes: 3

Views: 337

Answers (1)

ByteHamster
ByteHamster

Reputation: 4951

Use this:

TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.star_on_image, typedValue, true);
ImageButton star = ((ImageButton)findViewById(R.id.favorite_button_on));
star.setImageResource(typedValue.resourceId);

Upvotes: 3

Related Questions