2

假设我Activity的根布局中有背景。我希望在屏幕上放置一些按钮,这些按钮始终相对于屏幕位于同一位置。我怎样才能做到这一点?

我尝试使用dpsp但如果我在另一个屏幕上测试布局,一切都会崩溃。(所以,如果它在WVGA中没问题,它在QVGA中不起作用。我做错了什么吗?

这是我的布局 xml:

<?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"
        android:background="@drawable/menu_activity_bg" >
        <Button
            android:id="@+id/continueButton"
            android:layout_width="110sp"
            android:layout_height="30sp"
            android:layout_marginLeft="100sp"
            android:layout_marginTop="180sp"
            android:background="@drawable/menu_activity_continue" />
        <Button
            android:id="@+id/newGameButton"
            android:layout_width="130sp"
            android:layout_height="35dp"
            android:layout_marginLeft="90sp"
            android:layout_marginTop="220sp"
            android:background="@drawable/menu_activity_new_game" />
            <!-- ... -->
    </RelativeLayout>
4

2 回答 2

1

我对此的解决方案是拥有多种样式类型,我将它们放在 values-large、values-small、values-normal 和 values-xlarge 文件夹中。一个典型的条目将如下所示:

<resources>
<style name="bigText">
    <item name="android:textSize">60dp</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_marginTop">5dp</item>
    <item name="android:layout_marginBottom">5dp</item>
    <item name="android:textColor">#000000</item>
</style>
</resources>

然后我的布局 XML 看起来像:

<TextView
    android:id="@+id/somTextValue"
    style="@style/bigText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/someText" />

Having a number of these styles, I apply them to my objects that need to scale. Trial and error will allow me to find something that works well for all screen sizes.

于 2012-12-03T11:54:55.870 回答
0

I have one another 2 approaches:

  1. Use layout weight to your view so that it will take space accordingly

  2. Use of DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int height = metrics.heightPixels; int wwidth = metrics.widthPixels; This will give you width & height of screen then while creating give measurement in percentage e.g. 20% of width. It is helpful when you are dynamically creating UI.

于 2012-12-03T12:07:30.463 回答