363

在我调用该setCompoundDrawables方法后,没有显示复合 Drawable ..

Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
btn.setCompoundDrawables(myDrawable, null, null, null);

有什么想法吗?

4

10 回答 10

683

我需要使用setCompoundDrawablesWithIntrinsicBounds.

于 2011-07-06T16:24:25.923 回答
73

使用这个(我测试过)。效果很好

Drawable image = context.getResources().getDrawable( R.drawable.ic_action );
int h = image.getIntrinsicHeight(); 
int w = image.getIntrinsicWidth();   
image.setBounds( 0, 0, w, h );
button.setCompoundDrawables( image, null, null, null );
于 2014-10-19T08:03:04.537 回答
51

图像是空白的,因为它没有指定的边界。您可以使用setCompoundDrawables(),但在指定图像边界之前,使用Drawable.setBounds()方法

于 2012-02-13T07:20:28.890 回答
47

设置为顶部的示例:

view.setCompoundDrawablesWithIntrinsicBounds(
    null,
    getResources().getDrawable(R.drawable.some_img),
    null,
    null
);

参数顺序:(左,上,右,下)

于 2016-09-21T15:22:06.707 回答
24

再简单一点:

Drawable image = context.getResources().getDrawable(R.drawable.ic_action );
image.setBounds( 0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight() );
button.setCompoundDrawables( image, null, null, null );
于 2015-07-10T16:44:17.813 回答
17

由于您未指定边界,因此未显示图像,因此此处有 2 个选项。

第一种方法

使用setCompoundDrawablesWithIntrinsicBounds方法,如下图

Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
btn. setCompoundDrawablesWithIntrinsicBounds(myDrawable, null, null, null);

第二种方法

您可以在应用到 TextView 之前对 drawable 应用边界,如下所示

Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
myDrawable.setBounds( 0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
btn.setCompoundDrawables(myDrawable, null, null, null);

就是这样。

于 2020-05-08T19:41:55.620 回答
11

它在 API 22 中已弃用。

这段代码对我有用:

Drawable drawable = ResourcesCompat.getDrawable(getResources(),R.drawable.wen, null);
drawable.setBounds(0, 0, drawable.getMinimumWidth(),
drawable.getMinimumHeight());
tv.setCompoundDrawables(drawable, null, null, null);
于 2015-09-05T17:05:52.770 回答
4

在科特林:

1) 设置drawable

val drawable = ContextCompat.getDrawable(context!!,R.drawable.ic_image)?.apply {
    setBounds(0, 0, intrinsicWidth, intrinsicHeight)
}

或者

val drawable = ResourcesCompat.getDrawable(resources, R.drawable.ic_image, null)?.apply {
    setBounds(0, 0, minimumWidth, minimumHeight)
}

2) 设置TextView

textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)

或者

button.setCompoundDrawables(null, drawable, null, null)
于 2018-12-14T15:48:30.310 回答
3

对我来说setCompoundDrawablesWithIntrinsicBounds(Drawable, Drawable, Drawable, Drawable)不起作用。

我不得不使用setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)

于 2018-03-27T07:37:18.457 回答
2

Kotlin 示例:

    val myView = layoutInflater.inflate(R.layout.my_view, null) as TextView
    myView.setCompoundDrawablesWithIntrinsicBounds(0, myDrawable, 0, 0)
于 2018-06-08T19:32:32.123 回答