调用setCompoundDrawables()不会显示CompoundDrawable

调用setCompoundDrawables方法后,复合Drawable未显示。

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

任何想法吗?

90187 次浏览

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

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

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

再简单一点:

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

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

示例设置在顶部:

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

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

Kotlin的例子:

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

在芬兰湾的科特林:

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)

图像没有显示,因为你没有指定边界,所以你有两个选项。

1号方法

使用setCompoundDrawablesWithIntrinsicBounds方法,如下所示

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

2方法

你可以在应用到TextView之前对可绘制对象应用边界,如下所示

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

就是这样。

芬兰湾的科特林中使用数据绑定

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

,其中tvTimetextView,位置(Rigth,Top,Left,Bottom),关于绑定的更多信息在这里 https://stackoverflow.com/a/72360048/12272687 < / p >