首页 > 解决方案 > 当布局子项不适合时如何调整 LinearLayout 元素?

问题描述

例如,我有这些按钮,如下所示:

| [button1] [button2]     |
| [button3] [button4]     |

但是当我添加更多按钮时,它们不适合并且看起来像:

| [button1] [button2]     |
| [button3] [button4] [but|

结果,它水平滚动。

我尝试过使用LayoutParams布局权重,但我将一些按钮拉长,一些按钮变小了,它消除了按钮之间的间隙。我也尝试过ButtonBarLayout,但它改变了按钮的方向,这与我想要的完全不同。

这是我的尝试,它总是对元素进行加权,无论它们是否合适

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
     super.onMeasure(widthMeasureSpec, heightMeasureSpec);
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int) Utils.dp(getResources(), 96));
     params.weight = 1F;

     int childCount = this.getChildCount();
     for (int i = 0; i < childCount; i++) {
         View view = this.getChildAt(i);
         view.setLayoutParams(params);
     }
}

这是 XML(按钮行太长而无法容纳):

<com.tb24.fn.view.LockerRowLayout
    android:id="@+id/locker_wrap_slots"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <include
        android:id="@+id/locker_slot_wrap1"
        layout="@layout/slot_view" />

    <include
        android:id="@+id/locker_slot_wrap2"
        layout="@layout/slot_view" />

    <include
        android:id="@+id/locker_slot_wrap3"
        layout="@layout/slot_view" />

    <include
        android:id="@+id/locker_slot_wrap4"
        layout="@layout/slot_view" />

    <include
        android:id="@+id/locker_slot_wrap5"
        layout="@layout/slot_view" />

    <include
        android:id="@+id/locker_slot_wrap6"
        layout="@layout/slot_view" />

    <include
        android:id="@+id/locker_slot_wrap7"
        layout="@layout/slot_view" />
</com.tb24.fn.view.LockerRowLayout>

LockerRowLayout扩展LinearLayout

所以在示例中,我想让布局调整第二行按钮,但让第一行保持不变。我不想让它滚动,而是想让它们的宽度更小并动态截断它们,例如:

| [button1] [button2]     |
| [but.1] [but.2] [but.3] |

标签: javaandroid

解决方案


您不需要以编程方式设置动态宽度,而是可以在 xml 中一行内的所有按钮中使用android:layout_weight="1"android:layout_width="0dp",它应该自动调整它们的大小以完全适应整个宽度(我的意思是没有溢出)。


推荐阅读