Calling setCompoundDrawables() doesn't display

2019-01-16 04:31发布

问题:

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?

回答1:

I needed to be using setCompoundDrawablesWithIntrinsicBounds.



回答2:

Use This (I tested). It works good

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


回答3:

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:

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


回答5:

Example set to the top:

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

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



回答6:

It is deprecated in API 22.

This code is useful for me:

Drawable drawable = ResourcesCompat.getDrawable(getResources(),R.drawable.wen, null);
drawable.setBounds(0, 0, drawable.getMinimumWidth(),
drawable.getMinimumHeight());
tv.setCompoundDrawables(drawable, null, null, null);


回答7:

For me setCompoundDrawablesWithIntrinsicBounds(Drawable, Drawable, Drawable, Drawable) did not work.

I had to use setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0).



回答8:

Example with Kotlin:

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


回答9:

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)