如何使安卓应用适配所有屏幕尺寸

4

我有一个activity.xml文件,其中包含一个背景图和一个按钮,该按钮也有一个背景图,在普通屏幕上运行正常,但在xlarge或大屏幕上运行时,按钮的位置会改变。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@drawable/menu"
    android:layout_margin="@dimen/my_view_margin"
     >

    <LinearLayout
        android:layout_width="300px"
        android:layout_height="200px"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="172dp"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="60px"
            android:background="@drawable/bt"
            android:text="Button" />
    </LinearLayout>

</RelativeLayout>

以下是代码,下面是不同屏幕的图像。
抱歉,因为声望不够,无法添加图片。

首先,您应该开始使用“dp”值而不是“px”值。并且,阅读以下链接。这足以实现您所寻找的功能。http://developer.android.com/guide/practices/screens_support.html和http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html - Siddharth Lele
以下链接可以帮助您创建适用于多个屏幕的应用程序: 1. http://developer.android.com/training/multiscreen/screensizes.html 2. http://developer.android.com/guide/practices/screens_support.html 这些是Android官方文档,关于实现对多个屏幕尺寸的支持。 - Vipul Purohit
1
使用dp而不是px。为什么要在Relative布局中使用Linear布局?不要固定高度和宽度,这是大型设备的问题。 - Manish Srivastava
尝试我的答案,它应该在所有设备上都能正常工作。 - Manish Srivastava
6个回答

5

在所有布局中使用权重(weight)代替固定值,因为权重是屏幕上的一种百分比。在清单文件中,默认支持屏幕视图。

如果您认为有时不可能实现,则可以添加dimens值(包含dimens.xml的文件夹)。


3

2
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/my_view_margin"
    android:background="@drawable/menu"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_marginTop="170dp"
        android:layout_centerHorizontal="true"
        android:background="@drawable/bt"
        android:text="Button" />

</RelativeLayout>

1
<supports-screens android:smallScreens="true" 
          android:normalScreens="true" 
          android:largeScreens="true"
          android:xlargeScreens="true"
          android:anyDensity="true" />

将以下内容添加到您的应用程序清单文件中。

1
这不是问题。问题在于布局(layout)。 如果UI(用户界面)不被支持,他什么也看不到。 - Manish Srivastava

0

简单来说,使用相对布局和设置边距代码即可。设置每个文本视图、按钮等之间的边距,这样在每台手机上都会呈现相同的效果。

android:layout_marginTop="10dp" 
// change Top to Bottom, Left or Right for what you need.

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接