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

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

任何想法吗?


当前回答

在Kotlin中使用Databinding

binding.tvTime.setCompoundDrawablesWithIntrinsicBounds(
            ResourcesCompat.getDrawable(resources, android.R.drawable.ic_menu_recent_history, null),
            null,null,null)

哪里tvTime是textView和位置(右,上,左,下),更多关于绑定在这里 https://stackoverflow.com/a/72360048/12272687

其他回答

我需要使用setCompoundDrawablesWithIntrinsicBounds。

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

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

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

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

在芬兰湾的科特林:

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)

Kotlin的例子:

    val myView = layoutInflater.inflate(R.layout.my_view, null) as TextView
    myView.setCompoundDrawablesWithIntrinsicBounds(0, myDrawable, 0, 0)