activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F8F8FF"
android:padding="16dp"
tools:context=".MainActivity">
<!-- ImageButton no padding by XML -->
<ImageButton
android:id="@+id/ib"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:padding="0dp"
android:scaleType="fitCenter"
android:src="@drawable/share_stroke"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- ImageButton 16dp padding by XML -->
<ImageButton
android:id="@+id/ib2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:padding="16dp"
android:src="@drawable/share_stroke"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ib" />
<!-- ImageButton padding programmatically -->
<ImageButton
android:id="@+id/ib3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:src="@drawable/share_stroke"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ib2" />
<!-- ImageButton with default padding -->
<ImageButton
android:id="@+id/ib4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:src="@drawable/share_stroke"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ib3" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.cfsuman.androidtutorials;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageButton;
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
ImageButton ib3 = findViewById(R.id.ib3);
// Set padding for third ImageButton
// Set various pixels padding for ImageButton left,
// top, right and bottom side
ib3.setPadding(60,50,40,30);
}
}
