How to position button relative to the bottom of the screen?

I’m trying to position my button 50dp above the bottom of the screen. I know how to do this if I’m positioning it relative to the top of the screen with layout_marginTop but using layout_marginBottom doesn’t seem to be working, here’s my code:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

    <Button
        android:id="@+id/btn1"
        android:layout_width="296dp"
        android:layout_height="67dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="50dp"
        android:text="Button 1" />
    
</RelativeLayout>

This is what it’s showing:

enter image description here

And this is what I want it to show:

enter image description here

It feels like a dumb question, but does anyone know how to position a button relative to the bottom of the screen?

>Solution :

Only add

android:layout_alignParentBottom="true"

in RelativeLayout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
     >

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:gravity="center"
     android:layout_alignParentBottom="true"
        android:text="Button 1" />

</RelativeLayout>

But my Suggestion is use ConstraintLayout behalf of RelativeLayout

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:text="Button 1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Leave a Reply