Friday, August 28, 2015

How to set ImageView image from drawable 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="#e4e2e8"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set ImageView Image"
        />
    <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.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;


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) {
                /*
                    public void setImageDrawable (Drawable drawable)
                        Sets a drawable as the content of this ImageView.

                        Parameters
                        drawable : the Drawable to set, or null to clear the content
                */

                /*
                    public Drawable getDrawable (int id)
                        Return a drawable object associated with a particular resource ID.
                        Various types of objects will be returned depending on the
                        underlying resource -- for example, a solid color, PNG image,
                        scalable image, etc. The Drawable API hides these implementation details.
                */

                // Set ImageView image from drawable resource
                iv.setImageDrawable(getDrawable(R.drawable.android_image3));
            }
        });
  }
}

More android examples