Android - 如何使用XML在不同屏幕密度上的特定位置放置按钮

时间:2012-03-20 16:45:49

标签: android xml layout screen

我正在寻找一种借助XML将按钮放在特定位置的方法。

我希望有问题的按钮放在屏幕中间,只能放下。

即使更改屏幕密度,我也希望能够工作。

我尝试过使用android:layout_marginLeft =“10dp”,但是当我将密度从240降低到120时它并没有显示在同一位置。它在机器人开发页面上说dp应该被使用并且将随着屏幕,在这种情况下似乎不是。

按钮获得以下代码atm:

<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 个答案:

答案 0 :(得分:2)

查看以下代码,将按钮完全放在屏幕中间:

<?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>

如果我仍然希望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>

根据您的方便更改android:layout_marginTop="5dip"的值。