Wednesday, May 13, 2015

How to use ImageView in Android

Table of contents
  1. Android ImageView Example
    • ImageView XML
  2. Android ImageView Programmatically
    • ImageView LayoutParams
    • Add ImageView to RelativeLayout
    • ImageView setImageResource()
  3. ImageView Size XML
  4. Android ImageView Size Programmatically
  5. Android ImageView ScaleType
    • CENTER
    • CENTER_CROP
    • CENTER_INSIDE
    • FIT_CENTER
    • FIT_END
    • FIT_START
    • FIT_XY
    • MATRIX
  6. Android ImageView URL
    • AsyncTask
    • Android check internet connection
    • ImageView setImageBitmap()
    • BitmapFactory.decodeStream()

1. Android ImageView Example

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/animal"
        />
</RelativeLayout>

2. Android ImageView Programmatically

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Get the RelativeLayout reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);

        //Initialize a new ImageView Class/Widget
        ImageView iv = new ImageView(this);

        //Specify the ImageView image resource (drawable)
        iv.setImageResource(R.drawable.animal);

        //Setup the ImageView layout parameters (ImageView width and height)
        iv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        //Finally add the ImageView widget to RelativeLayout
        rl.addView(iv);;
   }
}

3. ImageView Size XML

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <ImageView
        android:id="@+id/iv"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:src="@drawable/animal"
        />
</RelativeLayout>

4. Android ImageView Size Programmatically

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Resize ImageView 200/200"
        android:onClick="OnButtonClicked"
        />
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/animal"
        android:layout_below="@id/btn"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   }

    public void OnButtonClicked(View v){
        //Get the widgets reference from XML layout
        ImageView iv = (ImageView) findViewById(R.id.iv);

        /*
            Here we call the ImageView requestLayout() method,
            because we are trying to setting the ImageView height and width after
            the layout already been laid out

            if want we setup the ImageView height and width in Activity onCreate()
            method, then we don't need to call ImageView requestLayout() method
        */
        iv.requestLayout();

        //Get the ImageView LayoutParams and assign ImageView height to 200
        iv.getLayoutParams().height = 200;

        //Get the ImageView LayoutParams and assign ImageView width to 200
        iv.getLayoutParams().width = 200;
    }
}

5. Android ImageView ScaleType

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:textColor="#ff3b49ff"
        android:textSize="15sp"
        />
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/animal"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Get the widgets reference from XML layout
        ImageView iv = (ImageView) findViewById(R.id.iv);
        TextView tv = (TextView) findViewById(R.id.tv);

        //Get the ImageView LayoutParams and assign ImageView height to 300 pixels
        iv.getLayoutParams().height = 300;

        //Get the ImageView LayoutParams and assign ImageView width to 300 pixels
        iv.getLayoutParams().width = 300;

        //************ Uncomment any section and comment other sections to view effect *********

        /*************************** ScaleType = CENTER ********************************/
        //Center the image in the view, but perform no scaling.
        //iv.setScaleType(ImageView.ScaleType.CENTER);
        //tv.setText("ScaleType = CENTER");
        /******************************************************************************/

        /*************************** ScaleType = CENTER_CROP ********************************/
        /*
            Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions
            (width and height) of the image will be equal to or larger than the corresponding
            dimension of the view (minus padding).
        */
        //iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        //tv.setText("ScaleType = CENTER_CROP");
        /******************************************************************************/

        /*************************** ScaleType = CENTER_INSIDE ********************************/
        /*
            Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions
            (width and height) of the image will be equal to or less than the corresponding
            dimension of the view (minus padding).
         */
        //iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        //tv.setText("ScaleType = CENTER_INSIDE");
        /******************************************************************************/

        /*************************** ScaleType = FIT_CENTER ********************************/
        //Scale the image using CENTER.
        //iv.setScaleType(ImageView.ScaleType.FIT_CENTER );
        //tv.setText("ScaleType = FIT_CENTER");
        /******************************************************************************/

        /*************************** ScaleType = FIT_END ********************************/
        //Scale the image using END.
        //iv.setScaleType(ImageView.ScaleType.FIT_END);
        //tv.setText("ScaleType = FIT_END");
        /******************************************************************************/

        /*************************** ScaleType = FIT_START ********************************/
        //Scale the image using START.
        //iv.setScaleType(ImageView.ScaleType.FIT_START);
        //tv.setText("ScaleType = FIT_START");
        /******************************************************************************/

        /*************************** ScaleType = FIT_XY ********************************/
        //Scale the image using FILL.
        //iv.setScaleType(ImageView.ScaleType.FIT_XY);
        //tv.setText("ScaleType = FIT_XY");
        /******************************************************************************/

        /*************************** ScaleType = MATRIX ********************************/
        //Scale using the image matrix when drawing.
        iv.setScaleType(ImageView.ScaleType.MATRIX);
        tv.setText("ScaleType = MATRIX");
        /******************************************************************************/
    }
}

6. Android ImageView URL

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:text="Load Image"
        />
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.InputStream;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Get the widgets reference from XML layout
        final ImageView iv = (ImageView) findViewById(R.id.iv);
        Button btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isNetworkConnected()){ // Check internet connection
                    //URl of image to display in ImageView
                    String urlOfImage = "https://www.google.com.bd/images/srpr/logo11w.png";

                    // Execute new task to download an image from web and set as ImageView image source
                    new ImageDownloadTask(iv).execute(urlOfImage);
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "No Network", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    //Custom method to check available active network
    public boolean isNetworkConnected(){
        ConnectivityManager cManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nInfo = cManager.getActiveNetworkInfo();

        Boolean result = true;
        if(nInfo == null)
        {
            //There are no active network.
            result = false;
        }
        return result;
    }

    /*
        New private class to download an image from web.
        AsyncTask enables proper and easy use of the UI thread. This class allows to perform
        background operations and publish results on the UI thread without having
        to manipulate threads and/or handlers.
     */
    private class ImageDownloadTask extends AsyncTask<String, Void, Bitmap>{

        //Initialize an ImageView Class/widget
        ImageView imageView;

        public ImageDownloadTask(ImageView iv){
            //Specify the initialized ImageView is same as the method calling ImageView
            this.imageView=iv;
        }

        //Background task to download image as bitmap
        protected Bitmap doInBackground(String... urls){
            String urlToDisplay = urls[0];
            Bitmap bmp = null;
            try{
                //Try to download the image from web as stream
                InputStream inputStream = new java.net.URL(urlToDisplay).openStream();
                //decodeStream(InputStream is) method decode an input stream into a bitmap.
                bmp = BitmapFactory.decodeStream(inputStream);

            }catch(Exception e){
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return bmp;
        }

        //do something with the result
        protected void onPostExecute(Bitmap result)
        {
            //Specify ImageView image source from downloaded image
            imageView.setImageBitmap(result);
        }
    }
}
AndroidManifest.xml [Required Permissions]

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
More android examples