Manuel Rizzo Manuel Rizzo - 9 months ago 40
Android Question

android studio divide layout in same

How can set a png icon on a button in the MainActivity?
I have to change this icon many times during the program, so I can't set the image in th xml code.

But in the xml is in the center of the button, so it's perfect and well stretched


In the MainActivity I don't know what to do

bt.setCompoundDrawablesWithIntrinsicBounds(null, x, null, null);

Answer Source

Use the below code:

Drawable top = getResources().getDrawable(R.drawable.x);
bt.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);

To Add the image at centre you can use imageButton:

Add the below image button in place of your button in layout xml.

        android:id="@+id/imageButton" />

Get the imageButton and set drawable:

ImageButton ib = (ImageButton)findViewById(;

Hope this helps.