Sunday, August 23, 2015

How to set ImageButton image 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="#c4c6ba"
    >
    <!--
        android:src
            Sets a drawable as the content of this ImageView.

            May be a reference to another resource,
            in the form "@[+][package:]type:name" or to a theme
            attribute in the form "?[package:][type:]name".

            May be a color value, in the form of
            "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

            This corresponds to the global attribute resource symbol src.
    -->
    <!-- Set the ImageButton image by XML-->
    <ImageButton
        android:id="@+id/ib"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image_button"
        />
    <!-- ImageButton as a simple color by XML-->
    <ImageButton
        android:id="@+id/ib2"
        android:layout_width="150dp"
        android:layout_height="75dp"
        android:src="@android:color/darker_gray"
        android:layout_below="@id/ib"
        />
    <!-- Set ImageButton image programmatically in java code-->
    <ImageButton
        android:id="@+id/ib3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/ib"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageButton;
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);
        ImageButton ib = (ImageButton) findViewById(R.id.ib);
        ImageButton ib2 = (ImageButton) findViewById(R.id.ib2);
        ImageButton ib3 = (ImageButton) findViewById(R.id.ib3);

        // Set the third image button image
        /*
            setImageResource (int resId)
                Sets a drawable as the content of this ImageButton.
         */
        ib3.setImageResource(R.drawable.image_button);
   }
}
More android examples