Android ImageButton set android:src=”@drawable” programmatically example

Dynamically setting up imagebutton image path in android application.

Android:src=” ” attribute is used to add image inside image button but some times app developer required some spacial type of functionality in their android application. So here is the complete step by step tutorial for Android ImageButton set android:src=”@drawable” programmatically example.

android-project-download-code-button

Android ImageButton set android:src=”@drawable” programmatically example.

Note: Put image into drawable-hdpi folder.

drawable hdpi folder

Download imagebutton image from below and put inside drawable-hdpi folder.

imagebutton_src
Code for MainActivity.java file.

 package com.imagebutoonsetsrcprogrammatically_android_examples.com;

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

public class MainActivity extends Activity {

 ImageButton ImageButtonSRC;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 ImageButtonSRC = (ImageButton)findViewById(R.id.imageButton1);
 
 // setting android:src=" " attribute dynamically.
 ImageButtonSRC.setImageResource(R.drawable.imagebutton_src);
 }
}

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.imagebutoonsetsrcprogrammatically_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"
 />

</RelativeLayout>

Screenshot :

Android ImageButton set android:src="@drawable" programmatically example

Click here to download Android ImageButton set android:src=”@drawable” programmatically example tutorial.

Leave a Reply

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