Friday, August 28, 2015

How to set a bitmap to ImageView in Android

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="10dp"
    tools:context=".MainActivity"
    android:background="#d9e6eb"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Bitmap To ImageView"
        />
    <!-- Programmatically set the ImageView image using Bitmap -->
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:layout_margin="10dp"
        android:layout_below="@id/btn"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.graphics.Bitmap;


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 RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        Button btn = (Button) findViewById(R.id.btn);
        final ImageView iv = (ImageView) findViewById(R.id.iv);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                    Bitmap decodeResource (Resources res, int id)
                        Synonym for decodeResource(Resources, int, android.graphics.BitmapFactory.Options)
                        with null Options.

                        Parameters
                            res : The resources object containing the image data
                            id : The resource id of the image data

                        Returns
                            The decoded bitmap, or null if the image could not be decoded.
                */
                /*
                    public abstract Resources getResources ()
                        Return a Resources instance for your application's package.
                */
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.elephant);

                // Set ImageView image as a Bitmap
                iv.setImageBitmap(bitmap);
            }
        });
  }
}

More android examples