java - 当布局子项不适合时如何调整 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] |
解决方案
您不需要以编程方式设置动态宽度,而是可以在 xml 中一行内的所有按钮中使用android:layout_weight="1"
和android:layout_width="0dp"
,它应该自动调整它们的大小以完全适应整个宽度(我的意思是没有溢出)。
推荐阅读
- css - 如何调整内容div的高度?
- python - 部署处理写入和更新事件的云功能
- javascript - Uncaught (in promise) TypeError: filter is not a function
- swift - Swift AutoLayout-锚未以编程方式应用
- reactjs - 创建 React App 测试覆盖率报告不涵盖 /src 中的所有文件
- c# - 如何在mvc orderBy中使用条件语句将0值移到最后
- excel - Excel PowerQuery 查询两次以在刷新时下载 excel 表 2 次
- c# - 当 ShowInTaskBar 设置为 false 时,最小化会在桌面上创建一个可见栏
- python - Sagemaker:ImportError:运行训练脚本时没有名为“pandas”的模块
- java - RestController 的抽象类自定义反序列化