Search code examples
androidandroid-layoutimagebutton

Android : Set padding of image in ImageButton programmatically


I have a problem with an ImageButton. The position of my image is not good into the ImageButton.

is there a way to fix that programmatically ?

enter image description here

    <ImageButton
        android:id="@+id/nouvelle_annonce_choose_image"
        style="?android:attr/borderlessButtonStyle"
        android:layout_width="170dp"
        android:layout_height="170dp"
        android:scaleType="center"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        android:background="@drawable/rounded_button"
        android:gravity="center_vertical|center_horizontal"
        android:src="@drawable/camera"
        android:text="hello"
        android:textColor="@color/blanc" />

rounded_button.xml :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/blanc"/>
    <stroke android:width="3sp" android:color="@color/blue_dark_normal" />
</shape>

Solution

  • You've started to do it, with the android:layout_marginTop. Either add a bottom margin, or else just us layout_margin, and you should be able to adjust the image as desired.

    In fact, it's because of the android:layout_marginTop that your image is off centered. It is putting a large margin at the top of the image, without compensating for it at the bottom.

    If margin doesn't work, then try playing with padding. Padding affects how things are aligned within the image. Padding is simply android:padding, or android:paddingBottom attributes.