Add border to Image Button in android programmatically

How to create border around image button using setBackgroundResource() method.

In this tutorial we are creating image button with border using XML layout file but we are setting up that XML as image button background to create border on button click event with setBackgroundResource() method. This method will gives us the ability to add any custom made XML file as current widget background. So here is the complete step by step tutorial for Add border to Image Button in android programmatically.

android-project-download-code-button

How to Add border to Image Button in android programmatically.

Code for MainActivity.java file.

 package com.imagebuttonborderprogrammatically_android_examples.com;

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

public class MainActivity extends Activity {

 Button button;
 ImageButton imagebutton;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 button = (Button)findViewById(R.id.button1);
 imagebutton = (ImageButton)findViewById(R.id.imageButton1);
 
 button.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 
 imagebutton.setBackgroundResource(R.layout.imagebutton_border);
 
 }
 });
 }

}

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.imagebuttonborderprogrammatically_android_examples.com.MainActivity" >

 <ImageButton
 android:id="@+id/imageButton1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="37dp"
 android:src="@drawable/demo_img" />

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/imageButton1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="38dp"
 android:text="Click here to Add border to Image Button in android programmatically" />

</RelativeLayout>

Code for imagebutton_border.xml file.

 <shape xmlns:android="http://schemas.android.com/apk/res/android">
 <stroke
 android:width="2dp"
 android:color="#fe0315" />
</shape>

Screenshots:

before-border

Add border to Image Button in android programmatically

Click here to download Add border to Image Button in android programmatically project with source code.