Android ImageView set image source src drawable dynamically using programming coding.
Setting up image drawable source from MainActivity.java programming file is very easy because some times there are so much images and app developer need to set image path on coding file. So here is the complete step by step tutorial for Android ImageView set image programmatically from drawable.
Android ImageView set image programmatically from drawable.
Put image inside drawable-hdpi folder.
Download image from below and copy inside drawable-hdpi folder.
Code for MainActivity.java file.
package com.imageviewimageprogrammatically_android_examples.com;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView imgSetDynamic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgSetDynamic = (ImageView)findViewById(R.id.imageView1);
//Setting up image path on activity run time.
imgSetDynamic.setImageResource(R.drawable.imageview_sample_image);
}
}
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.imageviewimageprogrammatically_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" /> </RelativeLayout>
Screenshot: