Sunday, August 23, 2015

How to add padding 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="#b1b3a9"
    >
    <!-- ImageButton with default padding -->
    <ImageButton
        android:id="@+id/ib"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image_button2"
        />
    <!-- ImageButton 20dp padding by XML -->
    <ImageButton
        android:id="@+id/ib2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image_button2"
        android:layout_below="@id/ib"
        android:padding="20dp"
        />
    <!-- ImageButton padding programmatically -->
    <ImageButton
        android:id="@+id/ib3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image_button2"
        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);
        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 padding for third ImageButton
        // Set 20 pixels padding both ImageButton left. top, right and bottom side
        ib3.setPadding(20,20,20,20);
   }
}
More android examples