Android - How to Place a Button at a Specific Position on Different Screen Levels Using XML

I am looking for a way to place a button at a specific location using XML.

I want the button in question to be placed in the middle of the screen, just squeeze it.

This I would like to work even when changing the screen density.

I tried to use android: layout_marginLeft = "10dp" but it doesn't show up in the same position when I decrease the density from 240 to 120. It says in the androids dev page that dp should be used and scaled with the screen, which in this case does not look.

Get the following atm code for the button:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/yowie_meny_utan_knappar">


<Button
    android:id="@+id/Button04"
    android:layout_width="100dp"
    android:layout_height="73dp"
    android:layout_gravity="center"
    android:layout_marginTop="200dp"
    android:layout_marginLeft="50dp"
    android:background="@drawable/play_button"
    >
  </Button>

      

+3


source to share


1 answer


Check out the code below which puts the button exactly in the middle of the screen:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <Button 
    android:layout_centerInParent="true" 
    android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</RelativeLayout>

      

If I still want the button to be slightly down from the middle, then one good way I know is to use an empty view of the text as a reference point for the button.



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >


    <TextView  android:layout_centerInParent="true" android:layout_width="wrap_content" android:id="@+id/textView1" 
     android:layout_height="wrap_content" android:text=" " ></TextView>
    <Button 
     android:layout_marginTop="5dip"
     android:layout_centerHorizontal="true"
    android:text="Button" android:layout_below="@id/textView1" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

</RelativeLayout>

      

Change the value android:layout_marginTop="5dip"

for convenience.

+2


source







All Articles