Add/Set bitmap in imageview in android programmatically

How to create imageview with bitmap image inside it from drawable resource folder.

In this tutorial we are setting up bitmap image inside imageview through MainActivity.java programming file using BitmapFactory.decodeResource method. This method will help us to retrieve drawable resource image and decode it into bitmap format. So here is the complete step by step tutorial for Add/Set bitmap in imageview in android programmatically.

android-project-download-code-button

Note:  Please download the sample image form below and put inside drawable-hdpi folder.

drawable hdpi folder

This is the sample demo image for this project:

sample_drawable_image

How to Add/Set bitmap in imageview in android programmatically.

Code for MainActivity.java file.

 package com.setbitmapinimageview_android_examples.com;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;


public class MainActivity extends Activity {

 ImageView imageview;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 imageview = (ImageView)findViewById(R.id.imageView1);
 
 Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.sample_drawable_image);

 imageview.setImageBitmap(bitmap);
 }

}

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

 <ImageView
 android:id="@+id/imageView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 />

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_above="@+id/imageView1"
 android:layout_centerHorizontal="true"
 android:text="Set bitmap in imageview in android"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:gravity="center" />

</RelativeLayout>

Screenshot:

Add/Set bitmap in imageview in android programmatically

Click here to download Add/Set bitmap in imageview in android programmatically project with source code.

Leave a Reply

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