7
XML     
<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton1"
        android:src="@drawable/image1"
        android:onClick="buttonClick"
    />

JAVA
--------------------
public void buttonClick(View v)
{
    Button aButton = (Button)v;
    aButton.setBackgroundResource(R.drawable.image2);
}

Here's what I've tried so far with no luck...

I want to be able to click the button and change the image to image2, there's also going to be other images i'll change it to based off of other variables. I'm just really stuck.. I'll continue looking at other questions and if I find an answer I'll post it here.

Brandon Romano
  • 1,022
  • 1
  • 13
  • 21

1 Answers1

19

Your buttonClick() needs fixing:

public void buttonClick(View v) 
{
 ImageButton aButton = (ImageButton)v;
 aButton.setImageResource(R.drawable.image2); 
} 

the View is an ImageButton, not a Button. The src attribute is updated via setImageResource, not setBackgroundResource.

CSmith
  • 13,318
  • 3
  • 39
  • 42
  • Thanks! I actually just figured this out, my second line was a lot sloppier though. Bravo! – Brandon Romano Aug 03 '12 at 20:48
  • Hey CSmith, I know this is 3 years later, but when I do this, my image is sized weirdly, and gets cut off. What should I do to fix that? Thanks – Ruchir Baronia Nov 11 '15 at 05:55
  • @RuchirBaronia in the XML of your activity, for your ImageButton: set android:scaleType="fitXY" to fill the ImageButton with the picture. Additionally, you can do android:padding="4dp" to completely fill the ImageButton. Hope it helps. – Jesús Hagiwara Nov 27 '18 at 05:20