Manuel Rizzo
Manuel Rizzo

Reputation: 615

Android Studio: PNG on Button

How can I 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 the xml code.

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

android:drawableTop="@drawable/x"

In the MainActivity I don't know what to do

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

Upvotes: 1

Views: 3313

Answers (2)

tahsinRupam
tahsinRupam

Reputation: 6405

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.

 <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton" />

Get the imageButton and set drawable:

ImageButton ib = (ImageButton)findViewById(R.id.imageButton);
ib.setImageResource(R.drawable.x); 

Hope this helps.

Upvotes: 1

Daniel Kvist
Daniel Kvist

Reputation: 3042

If you are targeting API level 17 or higher, you can accomplish this with just one simple line:

bt.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.x , 0, 0);

This method takes drawable resource ID's as arguments, so there is no need to get the drawable yourself using getDrawable(). Passing a 0 as argument means no icon on that side.

Good luck!

Upvotes: 0

Related Questions