如何在 Android 中带或不带屏幕按钮的设备上定位视图



我正在使用相对布局来显示我的主UI。在这个布局中,我在底部有 3 个按钮。它基本上看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
<!-- Some other content  ... -->
<!-- These are the 3 buttons at the bottom -->
<ImageButton
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentBottom="true"
    android:contentDescription="@string/button1"
    android:background="@drawable/button1"
    android:src="@drawable/button1" />
<ImageButton 
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    android:contentDescription="@string/button2"
    android:background="@drawable/button2"
    android:src="@drawable/button2" />
<ImageButton
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:contentDescription="@string/button3"
    android:background="@drawable/button3"
    android:src="@drawable/button3" />
</RelativeLayout>

现在,我在应用程序中所做的也是使用全屏布局(就像Android KitKat中的方式一样)。这意味着 UI 流在导航栏/屏幕按钮后面。

我试图实现的是:

  • 对于具有屏幕按钮的设备:3 个按钮应位于屏幕按钮的正上方:

  • 对于没有屏幕按钮的设备:3 个按钮应位于屏幕底部。

任何想法如何做到这一点?我可以使用fitSystemWindows吗?

相当简单。使用 FrameLayout,第一个子项将是 LinearLayout 中的应用 UI。第二个子项将是线性布局中的应用按钮栏。我们将使用权重来确保按钮栏始终位于设备屏幕的底部。

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <LinearLayout
        android:id="@+id/regularLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        ...
    </LinearLayout>
    <LinearLayout
        android:id="@+id/buttonLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <View
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
        <LinearLayout
            android:id="@+id/actualButtonBar"
            android:layout_width="match_parent"
            android:layout_height="60dp" >
        </LinearLayout>
    </LinearLayout>
</FrameLayout>

最新更新