Monday, August 24, 2015

How to add a border to an ImageButton 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="#9eb3a5"
    >
    <!-- ImageButton with default border, no border -->
    <ImageButton
        android:id="@+id/ib"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image_button3"
        />
    <!-- ImageButton with red border by XML -->
    <ImageButton
        android:id="@+id/ib2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image_button3"
        android:layout_toRightOf="@id/ib"
        android:background="@drawable/imageview_red_border"
        android:padding="10dp"
        />
    <!-- ImageButton with red border programmatically -->
    <ImageButton
        android:id="@+id/ib3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image_button3"
        android:layout_below="@id/ib"
        />
</RelativeLayout>
res/drawable/imageview_red_border.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <stroke
                android:color="#ff0000"
                android:width="2dp"
                />
        </shape>
    </item>
</selector>
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);
        final ImageButton ib = (ImageButton) findViewById(R.id.ib);
        final ImageButton ib2 = (ImageButton) findViewById(R.id.ib2);
        final ImageButton ib3 = (ImageButton) findViewById(R.id.ib3);

        // Set the background for third ImageButton
        // This background is empty and have a red colored border
        ib3.setBackground(getDrawable(R.drawable.imageview_red_border));
   }
}
More android examples