Reputation: 667
I put a drawable in a button, that works on Android 6 but not on Android 9 devices.
Same code, no exceptions, it’s just does not shows up. First I scale my drawable to fit in my button and change the color of the drawable, here is my code:
Integer scaleWidth = myButton.getWidth(); Integer scaleHeight =myButton.getHeight();
Drawable drawable = getResources().getDrawable(R.drawable.myDrawable);
Drawable wrappedDrawable = DrawableCompat.wrap(drawable); DrawableCompat.setTint(wrappedDrawable, iColor);
wrappedDrawable.setBounds(0, 0, (int) (wrappedDrawable.getIntrinsicWidth() * 0.5), (int) (wrappedDrawable.getIntrinsicHeight() * 0.5)); ScaleDrawable sd = new ScaleDrawable(wrappedDrawable, 0, scaleWidth, scaleHeight);
myButton.setCompoundDrawables(null, null, sd.getDrawable(), null);
EDIT:
this works:
Drawable drawable = getResources().getDrawable(R.drawable.xxx);
Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(wrappedDrawable, iColor);
wrappedDrawable.setBounds(0, 0, (int) (wrappedDrawable.getIntrinsicWidth() * 0.5), (int) (wrappedDrawable.getIntrinsicHeight() * 0.5));
Upvotes: 0
Views: 66
Reputation: 524
Do you really need to add the button drawable programmatically? Why not try my implementation which is to set the drawables in xml file? This code is already tested in Android 7.0 up until to Android 10.0. Here is my code:
<Button
android:id="@+id/btn_tax_receipt"
style="@style/page_button"
android:drawableTop="@drawable/ic_receipt_light"
android:text="@string/title_activity_tax_receipt"
android:textStyle="bold"
tools:layout_editor_absoluteX="27dp"
tools:layout_editor_absoluteY="225dp" />
You can change the color of the drawable by changing the color value of android:drawableTint
OR use this easier approach:
Upvotes: 2