Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing image dynamically in an ImageButton

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.

like image 490
Brandon Romano Avatar asked Aug 03 '12 20:08

Brandon Romano


1 Answers

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.

like image 103
CSmith Avatar answered Oct 02 '22 05:10

CSmith