动态对齐视图权重 - Android

时间:2013-08-20 07:56:16

标签: android android-layout android-ui

用例:

我有一个水平视图H,它包含5个按钮(A,B,C,D& E);在H中占用相同的空间。现在,根据某些业务逻辑,这些按钮中的每一个都可能是可见的。如果一个按钮不可见,其余的按钮应该平等对齐。

现在问题是如果我给每个按钮赋予特定的权重,那么我必须编写2 ^ 5 if-else个案来为按钮分配单独的权重。在Android中没有一种方法可以让所有这些按钮自行调整它们自己占用相同的空间。确切地说,这个想法只是写出5个案例,其中我使按钮可见或不可见,而静止视图自己对齐。我不能使用换行内容,因为这些按钮包含不同长度的文本,我希望按钮占用相同的空间而不是文本。

有没有办法做到这一点?我非常感谢这里的任何帮助。

2 个答案:

答案 0 :(得分:3)

指定所有按钮的权重(例如1),但不要为容器指定权重和。现在,当您需要隐藏按钮时,将其可见性设置为GONE,其他按钮将同等调整大小以占用可用空间。

答案 1 :(得分:0)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_weight="1" />

    <Button
        android:layout_width="fill_parent"
        android:layout_weight="1" />

    <Button
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:visibility="gone" />

</LinearLayout>

现在,如果您将第三个按钮设置为可见,则另外两个按钮将调整大小以在屏幕上显示3个按钮。水平布局中的视图相同:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="horizontal" >

    <Button
        android:layout_height="fill_parent"
        android:layout_weight="1" />

    <Button
        android:layout_height="fill_parent"
        android:layout_weight="1" />

    <Button
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:visibility="gone" />

</LinearLayout>
相关问题