Issue
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?
Solution
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);
Answered By - ByteHamster
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.