Change ImageButton image programmatically android

Replace another uploaded ImageButton image at application run time dynamically via coding.

ImageButton image can be easily replaceable through MainActivity.java programming file. So here is the complete step by step tutorial for Change ImageButton image programmatically android.

android-project-download-code-button

Note: Put both images inside drawable-hdpi folder.

drawable hdpi folder

Download both images from below and copy inside drawable-hdpi folder.

How to Change ImageButton image programmatically android.

Code for MainActivity.java file.

 package com.imagebuttonchangeimage_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity {

 ImageButton ImgButton;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 ImgButton = (ImageButton)findViewById(R.id.imageButton1);
 
 ImgButton.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 ImgButton.setImageResource(R.drawable.imagebutton_image_2);
 
 }
 });
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.imagebuttonchangeimage_android_examples.com.MainActivity" >

 <ImageButton
 android:id="@+id/imageButton1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:src="@drawable/imagebutton_image_1" />

</RelativeLayout>

Screenshot before ImageButton click :

change_imagebutton_1

Change ImageButton image programmatically android

Click here to download Change ImageButton image programmatically android project.

Leave a Reply

Your email address will not be published. Required fields are marked *