Android - How to place a button on a specific position on different screen densities with XML

浪子不回头ぞ 提交于 2020-02-03 08:48:07

问题


I am looking for a way to place a button on a specific spot with the help of XML.

I want the button in question to be placed in the middle of the screen, only abit down.

This I would like to be working even when changing screen densities.

I have tried using android:layout_marginLeft="10dp", but it doesnt show up at the same position when i lower the densities from 240 till 120. It says on androids dev page that dp should be used and will scale with the screen, which in this case doesnt seem to be.

Got the following code atm 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>

回答1:


Check out the below code which places the button exactly at 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 a little bit down from the middle, the one good way I know is to use an empty text view 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 of android:layout_marginTop="5dip" to your convenience.



来源:https://stackoverflow.com/questions/9791194/android-how-to-place-a-button-on-a-specific-position-on-different-screen-densi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!