Search code examples
androidandroid-studiobuttonlayoutmargins

layout_marginTop in Android Studio


I am trying to create a login page for an app in Android Studio. The XML code for the page is -

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/colorPrimary"
    tools:context=".LoginChoice">


    <Button
        android:id="@+id/userbtn"
        android:layout_width="100dp"
        android:layout_height="30dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="450dp"
        android:onClick="userloginIntent"
        android:adjustViewBounds="true"
        android:background="@drawable/user_login_button_small"
        app:strokeColor="@android:color/white" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/driverbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/white"
        android:onClick="driverloginIntent"
        android:paddingHorizontal="10dp"
        android:text="@string/driver_login"
        android:background="@drawable/buttonbg1"
        android:layout_marginVertical="20dp"
        android:layout_below="@+id/userbtn"/>

</RelativeLayout>

The problem here is that the Buttons that I am using, appear much lower on running the app in my phone than they do in the Design area in Android Studio. Here's how it looks in android studio- enter image description here

And here is a screenshot of when I run the app on my phone- enter image description here

Why is this happening and what can I do to fix it?


Solution

  • In Android Studio, you can choose the device that you are using to visualize your layout.xml, the default device may not be have the dimensions as your physical device. You can change it or add a device definition to match your desired device. Also, you could use Layout Validation to see a more accurate preview of your design.

    Remember that you are using dp as a unit measure, not standard pixels.

    enter image description here