Search code examples
androidandroid-imageviewandroid-fileandroid-bitmap

Programmatically change background / source for ImageView in android


I am creating an android app where I want to display an image full screen. The image is stored in the internal storage of an android phone and the image to be displayed can vary each time. In the layout XML file for that activity, I added an image view tag as shown below:

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/android" />

What shall I type for the android:src ? Any help & suggestions would be appreciated.


Solution

  • Optional: Remove the line

    android:src="@drawable/android"
    //This can be kept as a default image in case the file you want does not exist.
    

    from the XML layout. Since the image may vary every time, you need to use

    File file = new  File("/sdcard/Images/test_image.jpg");
    
    if(file.exists()){
    
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    
        ImageView image = (ImageView) findViewById(R.id.imageview1);
    
        image.setImageBitmap(bitmap);
    
    }