Android Imagebutton change Image OnClick

user1205415 picture user1205415 · Sep 3, 2012 · Viewed 118.8k times · Source

I just added a new drawable folder under res folder. In the drawable folder, i copied the ic_launcher.png file from drawable-hdpi folder. I wanna change the standard ImageButton image through the new one when i press the button. I wrote some code, but when i start the app, it crashes.

Button imgButton; 

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    findViewById(R.id.imgButton).setOnClickListener(imgButtonHandler);      
}

View.OnClickListener imgButtonHandler = new View.OnClickListener() {

    public void onClick(View v) {

        imgButton.setBackgroundResource(R.drawable.ic_launcher);

    }
};

EDIT: I changed to this, and this also not works.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imgButton = (Button) findViewById(R.id.imgButton);
    imgButton.setOnClickListener(imgButtonHandler);
}


View.OnClickListener imgButtonHandler = new View.OnClickListener() {

    public void onClick(View v) {
        imgButton.setBackgroundResource(R.drawable.ic_launcher);

    }
};

EDIT 2: THIS WORKS. Thanks to all.

ImageButton button;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button= (ImageButton)findViewById(R.id.imgButton);
    button.setOnClickListener(imgButtonHandler);
}


View.OnClickListener imgButtonHandler = new View.OnClickListener() {

    public void onClick(View v) {
        button.setBackgroundResource(R.drawable.ic_launcher);

    }
};

Answer

Yassine Souabni picture Yassine Souabni · Jan 8, 2014

This misled me a bit - it should be setImageResource instead of setBackgroundResource :) !!

The following works fine :

ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);       
 btn.setImageResource(R.drawable.actions_record);

while when using the setBackgroundResource the actual imagebutton's image stays while the background image is changed which leads to a ugly looking imageButton object

Thanks.