Create ImageButton programmatically android example tutorial

Create ImageButton inside android application dynamically using MainActivity.java coding file.

ImageButton are most commonly used inside android apps because with the help of image buttons application developer can easily add buttons images created by Photoshop into android apps. So here is the complete step by step tutorial for Create ImageButton programmatically android example tutorial.

android-project-download-code-button

Note: Copy the image inside drawable-hdpi folder.

drawable hdpi folder

Download sample button image from below and put inside drawable hdpi folder.

imagebutton_sample_image

How to Create ImageButton programmatically android example tutorial.

Code for MainActivity.java file.

 package com.imagebuttonprogrammatically_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;


public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 ImageButton imagebutton = new ImageButton(MainActivity.this);
 RelativeLayout relativelayout = (RelativeLayout)findViewById(R.id.relativelayout);
 LinearLayout.LayoutParams params = new LinearLayout
 .LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
 
 // Add image path for imagebutton from drawable folder.
 imagebutton.setImageResource(R.drawable.imagebutton_sample_image);
 imagebutton.setLayoutParams(params); 
 relativelayout.addView(imagebutton); 
 
 imagebutton.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 Toast.makeText(MainActivity.this, "Clicked on image button", Toast.LENGTH_LONG).show();
 
 }
 });
 }
}

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:id="@+id/relativelayout"
 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.imagebuttonprogrammatically_android_examples.com.MainActivity" >

</RelativeLayout>

Screenshot :

Create ImageButton programmatically android example tutorial

Click here to download Create ImageButton programmatically android example tutorial project.