简体   繁体   中英

Android 9 drawable in Button not showing

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));

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM