简体   繁体   English

按钮中的 Android 9 drawable 未显示

[英]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.我在按钮中放置了一个 drawable,它适用于 Android 6 但不适用于 Android 9 设备。

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:首先,我缩放我的 drawable 以适应我的按钮并更改 drawable 的颜色,这是我的代码:

Integer scaleWidth = myButton.getWidth();整数 scaleWidth = myButton.getWidth(); Integer scaleHeight =myButton.getHeight();整数 scaleHeight =myButton.getHeight();

Drawable drawable = getResources().getDrawable(R.drawable.myDrawable); Drawable drawable = getResources().getDrawable(R.drawable.myDrawable);

Drawable wrappedDrawable = DrawableCompat.wrap(drawable);可绘制的wrappedDrawable = DrawableCompat.wrap(drawable); DrawableCompat.setTint(wrappedDrawable, iColor); DrawableCompat.setTint(wrappedDrawable, iColor);

wrappedDrawable.setBounds(0, 0, (int) (wrappedDrawable.getIntrinsicWidth() * 0.5), (int) (wrappedDrawable.getIntrinsicHeight() * 0.5)); WrappedDrawable.setBounds(0, 0, (int) (wrappedDrawable.getIntrinsicWidth() * 0.5), (int) (wrappedDrawable.getIntrinsicHeight() * 0.5)); ScaleDrawable sd = new ScaleDrawable(wrappedDrawable, 0, scaleWidth, scaleHeight); ScaleDrawable sd = new ScaleDrawable(wrappedDrawable, 0, scaleWidth, scaleHeight);

myButton.setCompoundDrawables(null, null, sd.getDrawable(), null); 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?你真的需要以编程方式添加按钮 drawable 吗? Why not try my implementation which is to set the drawables in xml file?为什么不试试我的实现,即在 xml 文件中设置可绘制对象? This code is already tested in Android 7.0 up until to Android 10.0.这段代码已经在 Android 7.0 中测试过,直到 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您可以通过更改android:drawableTint的颜色值来更改 drawable 的颜色

OR use this easier approach:或者使用这种更简单的方法:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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