Sunday, August 23, 2015

How to change ImageButton background color 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"
    >
    <!-- No background color defined -->
    <ImageButton
        android:id="@+id/ib"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/transparent_image_button"
        />
    <!-- ImageButton background color orange by XML-->
    <ImageButton
        android:id="@+id/ib2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/transparent_image_button"
        android:background="#ffa62b"
        android:layout_below="@id/ib"
        />
    <!-- ImageButton background color blue programmatically -->
    <ImageButton
        android:id="@+id/ib3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/transparent_image_button"
        android:layout_toRightOf="@id/ib"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
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 background color
        ib3.setBackgroundColor(Color.parseColor("#666bff"));
   }
}
More android examples