Issue
I subclassed Button
. From within that class I try to change the color programmatically.
RippleDrawable draw = (RippleDrawable) getContext().getApplicationContext()
.getResources().getDrawable(R.drawable.raised_btn);
this.setBackground(draw);
Looks great so far..
But then I press the button, and it's the most random of colors. Nowhere have I specified these pinkish colors. If I set this drawable as the background via XML (android:background="@drawable/raised_btn"
), then I have no issues. I need to set it programmatically though.
My RippleDrawable
- raised_btn.xml
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?attr/colorControlHighlight">
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="@dimen/button_inset_horizontal_material"
android:insetTop="@dimen/button_inset_vertical_material"
android:insetRight="@dimen/button_inset_horizontal_material"
android:insetBottom="@dimen/button_inset_vertical_material">
<shape android:shape="rectangle">
<corners android:radius="@dimen/control_corner_material" />
<solid android:color="@color/tan"/>
<padding android:left="@dimen/button_padding_horizontal_material"
android:top="@dimen/button_padding_vertical_material"
android:right="@dimen/button_padding_horizontal_material"
android:bottom="@dimen/button_padding_vertical_material" />
</shape>
</inset>
</ripple>
How do I achieve the correct ripple effect when setting the RippleDrawable
background programmatically?
Solution
The Resources
object doesn't know about the activity theme. You need to obtain the drawable from the Context
or pass a Theme
into Resources.getDrawable(int,Theme)
in order for theme attributes to be resolved.
Context ctx = getContext();
// The simplest use case:
RippleDrawable dr1 = (RippleDrawable) ctx.getDrawable(R.drawable.raised_btn);
// Also valid:
Resources res = ctx.getResources();
RippleDrawable dr2 =
(RippleDrawable) res.getDrawable(R.drawable.raised_btn, ctx.getTheme());
// If you're using support lib:
Drawable dr3 = ContextCompat.getDrawable(ctx, R.drawable.raised_btn);
Also, there's no reason to be using the application context here. If anything, that gives you a higher chance that the theme that you're using to resolve attributes won't match the theme that was used to inflate whatever view you're passing the drawable in to.
Answered By - alanv
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.