android - 更改可绘制对象并将其设置为 drawableLeft

标签 android bitmap drawable

我在 LinearLayout 中有一个按钮,我在其中分配了一个 XML 中的 drawableLeft,如下所示:

<Button android:id="@+id/button_news"
    style="@style/main_button"
    android:drawableLeft="@drawable/news"
    android:text="@string/button_news" />

这工作正常,按钮看起来像预期的那样。

enter image description here

我想以编程方式更改图像以显示可用新闻的数量。这是我的代码:

private void updateNewsButton()
{
    // load the original bitmap and draw the number of news on it to show it
    Paint paint = new Paint();
    paint.setColor( Statics.COLOR_GENERAL_HIGHLIGHT );
    paint.setTextAlign( Paint.Align.CENTER );
    paint.setTextSize( 24 );
    paint.setTypeface( Typeface.defaultFromStyle( Typeface.BOLD ) );
    paint.setAntiAlias( true );

    Bitmap bmp = BitmapFactory.decodeResource( getResources(), R.drawable.news ).copy( Config.ARGB_8888, true );
    Canvas canvas = new Canvas( bmp );
    int count = 5;    // TODO: load from database
    canvas.drawText( Integer.toString( count ), bmp.getWidth() / 2, bmp.getHeight() / 2, paint );
    Drawable d = new BitmapDrawable( bmp );
    _btnNews.setCompoundDrawables( d, null, null, null );
}

运行上述代码后,按钮上的图像就消失了。我看不出我做错了什么,因为我之前对 ImageView 使用过类似的技术。除了最后两行外,其他一切都一样。对于 ImageView,我直接分配位图:

...
imageView.setImageBitmap( bmp );

我需要在这里使用 drawableLeft,因为还有一些其他的按钮,所以我不能再使用 ImageView。

知道我的代码有什么问题吗?

最佳答案

要以编程方式将图像放在按钮的左侧,请使用下面的代码

Button button = (Button) findViewById(R.id.mybutton);   
button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.img, 0, 0, 0);

位置是这样的(左,上,右,下)

关于android - 更改可绘制对象并将其设置为 drawableLeft,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112118/

相关文章:

android - 可从 mdpi 加载而不是 hdpi 加载

android - 通过 AppCompat 在 pre-lollipop 上的可绘制对象中使用 colorPrimary

android - 使用 ShapedDrawable 将 ColorFilter 应用于 ImageView

fragment 中的 Android ListView

android - 相机预览没有重新启动?

android - Android 性能中的 Kotlin 枚举类

image - 如何从这个文件头计算位图的宽度和高度?

c# - 将布局保存到位图(Xamarin)

java - 对 Bitmap 中的像素值感到困惑(使用 setPixel 预乘颜色)

android - 尝试 jetpack compose 时显示错误 : compiler backend and cannot be loaded by the old compiler