Android 对话框高度

Android Dialog Height

我正在尝试设置一个简单的对话框,但我似乎无法控制高度。它始终是最大屏幕高度。有什么方法可以让它正确包装到内容中吗?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/save"
        android:id="@+id/buttonSave"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:textAlignment="center"
        style="?attr/borderlessButtonStyle"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@android:string/cancel"
        android:id="@+id/buttonCancel"
        android:layout_alignParentBottom="true"
        android:layout_toStartOf="@+id/buttonSave"
        style="?attr/borderlessButtonStyle"/>

</RelativeLayout>

.

final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.save_dialog);
dialog.setTitle(R.string.saveAs);
dialog.show();

您的 XML 中有 android:layout_alignParentBottom="true" 个。这会强制您的 Button 位于可用的 space 的最底部,从而有效地使 RelativeLayout 具有 match_parent layout_height 行为wrap_content 个。

另一种方法是使用 LinearLayoutGridLayout。 类似这样的东西可以解决问题:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <!-- 
    The rest of your layout can go here 
    with a layout_height of 0dp and a layout_weight of 1
    if you want your buttons to dock themselves at the bottom of the dialog
    -->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@android:string/cancel"
            android:id="@+id/buttonCancel"
            style="?attr/borderlessButtonStyle"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/save"
            android:id="@+id/buttonSave"
            android:textAlignment="center"
            style="?attr/borderlessButtonStyle"/>
    </LinearLayout>
</LinearLayout>