调用setCompoundDrawables()不会显示Compound Drawable

hun*_*erp 305 android android-layout android-drawable

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

Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
btn.setCompoundDrawables(myDrawable, null, null, null);
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

hun*_*erp 597

我需要使用setCompoundDrawablesWithIntrinsicBounds.

  • @ user1324936 setCompoundDrawablesWithIntrinsicBounds在**API Level 3**中添加 (10认同)
  • 需要api 17所以Drawable.setBounds()可能会更好 (7认同)
  • 非常感谢..这对我有用..我可能知道这两者之间有什么区别吗? (6认同)

小智 66

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

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 );
Run Code Online (Sandbox Code Playgroud)

  • 你能提供一个来源吗?我见过的所有文档都表明[自API 1以来可用](https://developer.android.com/reference/android/widget/TextView.html). (5认同)

teo*_*tik 48

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


And*_*rey 37

示例设置为顶部:

view.setCompoundDrawablesWithIntrinsicBounds(
    null,
    getResources().getDrawable(R.drawable.some_img),
    null,
    null
);
Run Code Online (Sandbox Code Playgroud)

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


Ale*_*ecs 22

再简单一点:

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


Asa*_*hry 12

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

第一种方法

使用setCompoundDrawablesWithIntrinsicBounds方法,如下图

Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
btn. setCompoundDrawablesWithIntrinsicBounds(myDrawable, null, null, null);
Run Code Online (Sandbox Code Playgroud)

方法二

可以在应用到TextView之前先对drawable应用bounds,如下图

Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
myDrawable.setBounds( 0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
btn.setCompoundDrawables(myDrawable, null, null, null);
Run Code Online (Sandbox Code Playgroud)

就是这样。


小智 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);
Run Code Online (Sandbox Code Playgroud)