DEV Community

Mateusz Budnik
Mateusz Budnik

Posted on

Setting compound drawable size

In many cases, we need to have some image next to the text. We can do that using designer view by setting e.q. drawableLeft text field property:
Zrzut ekranu 2021-04-16 o 18.51.21

But this approach is sometimes not the best. We don't have full control over the drawable position and size. Of course, there is some way of changing image size like scaling the entire view, but sometimes it may make matters even worse.

An alternative way of doing that is setting compound drawable programmatically. The code below shows how to do it.

final float density = getResource().getDisplayMetrics().density;
final Drawable drawable = getResources().getDrawable(R.drawable.some_drawable);
final int width = Math.round(12 * density);
final int height = Math.round(12 * density);
drawable.setBounds(0, 0, width, height);
Enter fullscreen mode Exit fullscreen mode
view.setCompoundDrawables(drawable, null, null, null);
Enter fullscreen mode Exit fullscreen mode

Discussion (0)