调用setCompoundDrawables()不会显示Compound Drawable

问题描述 投票:288回答:9

在我调用setCompoundDrawables方法后,未显示复合Drawable ..

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

有什么想法吗?

android android-layout android-drawable
9个回答
587
投票

63
投票

使用此(我测试过)。它运作良好

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

46
投票

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


33
投票

示例设置为顶部:

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

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


22
投票

再简单一点:

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

10
投票

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


2
投票

在Kotlin:

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
投票

Kotlin的例子:

    val myView = layoutInflater.inflate(R.layout.my_view, null) as TextView
    myView.setCompoundDrawablesWithIntrinsicBounds(0, myDrawable, 0, 0)
© www.soinside.com 2019 - 2024. All rights reserved.