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

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

任何想法吗?


当前回答

在芬兰湾的科特林:

1)设置可绘制:

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

or

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

2)设置TextView:

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

or

button.setCompoundDrawables(null, drawable, null, null)

其他回答

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

我必须使用setcompounddrawableswithintrinsic icbounds(0,0,0,0)。

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

在芬兰湾的科特林:

1)设置可绘制:

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

or

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

2)设置TextView:

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

or

button.setCompoundDrawables(null, drawable, null, null)

再简单一点:

Drawable image = context.getResources().getDrawable(R.drawable.ic_action );
image.setBounds( 0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight() );
button.setCompoundDrawables( image, null, null, null );

示例设置在顶部:

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

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