Create ImageView programmatically android example tutorial

Insert imageView inside android app using dynamically coding via MainActivity file.

Dynamically creating imageView using coding file through MainActivity.java programming file is very easy and useful because some time android app developer need to create imageview at application run time and set its properties so that can be only possible through programmatically method. So here is the complete step by step tutorial for Create ImageView programmatically android example tutorial.

android-project-download-code-button

How to Create ImageView programmatically android example tutorial.

Copy your image inside drawable-hdpi folder.

drawable hdpi folder

Download below image and put it into drawable folder.

demo_new_image
Code for MainActivity.java file.

 package com.imageviewprogrammatically_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 ImageView imageview = new ImageView(MainActivity.this);
 RelativeLayout relativelayout = (RelativeLayout)findViewById(R.id.relativeLayout);
 LinearLayout.LayoutParams params = new LinearLayout
 .LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
 
 // Add image path from drawable folder.
 imageview.setImageResource(R.drawable.demo_new_image);
 imageview.setLayoutParams(params); 
 relativelayout.addView(imageview); 
 
 }
}

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.imageviewprogrammatically_android_examples.com.MainActivity"
 android:id="@+id/relativeLayout" >

</RelativeLayout>

Screenshot:

Create ImageView programmatically android example tutorial

Click Here to download Create ImageView programmatically android example tutorial project.

Leave a Reply

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