Вызов setCompoundDrawables () не отображает составной Drawable - PullRequest
296 голосов
/ 06 июля 2011

После вызова метода setCompoundDrawables составной Drawable не отображается ..

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

Есть мысли?

Ответы [ 9 ]

585 голосов
/ 06 июля 2011

Мне нужно было использовать setCompoundDrawablesWithIntrinsicBounds.

63 голосов
/ 19 октября 2014

Используйте это (я проверял).Хорошо работает

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 голосов
/ 13 февраля 2012

Изображение пустое, потому что оно не имеет указанных границ. Вы можете использовать setCompoundDrawables(), но перед тем, как указать границы изображения, используйте Drawable.setBounds() метод

31 голосов
/ 21 сентября 2016

Пример установлен в начало:

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

порядок аргументов: (слева, сверху, справа, снизу)

21 голосов
/ 10 июля 2015

Снова немного проще:

Drawable image = context.getResources().getDrawable(R.drawable.ic_action );
image.setBounds( 0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight() );
button.setCompoundDrawables( image, null, null, null );
9 голосов
/ 05 сентября 2015

устарело в 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 голосов
/ 14 декабря 2018

В 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)
2 голосов
/ 27 марта 2018
1 голос
/ 08 июня 2018

Пример с Kotlin:

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