Calling setCompoundDrawables() doesn't display

2019-01-16 04:09发布

After I call the setCompoundDrawables method, the compound Drawable is not shown..

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

Any thoughts?

9条回答
Lonely孤独者°
2楼-- · 2019-01-16 04:37

Example with Kotlin:

    val myView = layoutInflater.inflate(R.layout.my_view, null) as TextView
    myView.setCompoundDrawablesWithIntrinsicBounds(0, myDrawable, 0, 0)
查看更多
我只想做你的唯一
3楼-- · 2019-01-16 04:44

Image is blank because it hasn't got specified bounds. You may use setCompoundDrawables() but before you should specify image's bounds, using Drawable.setBounds() method

查看更多
聊天终结者
4楼-- · 2019-01-16 04:44

A little bit simpler again:

Drawable image = context.getResources().getDrawable(R.drawable.ic_action );
image.setBounds( 0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight() );
button.setCompoundDrawables( image, null, null, null );
查看更多
forever°为你锁心
5楼-- · 2019-01-16 04:49

In Kotlin:

1) Set drawable:

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) Set TextView:

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

or

button.setCompoundDrawables(null, drawable, null, null)
查看更多
女痞
6楼-- · 2019-01-16 04:54
看我几分像从前
7楼-- · 2019-01-16 04:54

Example set to the top:

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

arguments order: (left, top, right, bottom)

查看更多
登录 后发表回答