android-constraintlayout - 添加约束以编程方式查看
问题描述
我在约束布局中膨胀了以下视图。看法 :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorPrimary"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".25"
android:text="menu"/>
<android.support.v7.widget.SearchView
android:layout_width="0dp"
android:layout_weight="1"
android:layoutDirection="rtl"
android:layout_height="match_parent">
</android.support.v7.widget.SearchView>
</LinearLayout>
使用以下代码将视图添加到约束布局:
ConstraintLayout constraintLayout = findViewById(R.id.root);
View inflatedLayout= inflater.inflate(R.layout.menu, constraintLayout, false); constraintLayout.addView(inflatedLayout);
视图移动到屏幕顶部,因为没有约束。它与布局顶部的工具栏重叠。工具栏被简单地限制在父级的顶部,其 id 为android:id="@+id/toolbar"
如何以编程方式添加约束,以便将膨胀视图约束在工具栏下方。我使用约束集将约束添加到膨胀视图,如下所示:
LayoutInflater inflater = LayoutInflater.from(PaymentStatus2.this);
ConstraintLayout constraintLayout = findViewById(R.id.nested);
View inflatedLayout= inflater.inflate(R.layout.menu, constraintLayout, false);
constraintLayout.addView(inflatedLayout);
ConstraintSet set = new ConstraintSet();
set.connect(constraintLayout.getId(),ConstraintSet.TOP,inflatedLayout.getId(),ConstraintSet.TOP,50);
set.connect(constraintLayout.getId(),ConstraintSet.START,inflatedLayout.getId(),ConstraintSet.START,0);
set.applyTo(constraintLayout);
在第一条连接线中,我将父级顶部连接到膨胀视图的顶部并设置 50dp 的边距,这应该符合我将其保持在高度为 50dps 的工具栏下方但不会反映在布局中的目的。认为该视图需要至少两个约束,我进行第二个连接仍然无法正常工作。这是它的样子:
膨胀的布局仍然移动到顶部,就好像没有约束一样。
解决方案
对于其他坚持这一点的人,我发现了它是如何完成的。膨胀布局添加它然后克隆布局,然后你需要连接所有四个约束端然后它才会起作用。
connect 函数有五个参数(i)视图的视图 id,(ii)约束方向,(iii)另一个视图 id,(iv)约束方向,(v)边距
ConstraintLayout constraintLayout = findViewById(R.id.nested);
View inflatedLayout= inflater.inflate(R.layout.menu, constraintLayout , false);
inflatedLayout.setLayoutParams(new ConstraintLayout.LayoutParams(0,0));
constraintLayout.addView(inflatedLayout,0);
ConstraintSet set = new ConstraintSet();
set.clone(constraintLayout);
set.connect(inflatedLayout.getId(),ConstraintSet.TOP,toolbar.getId(),ConstraintSet.BOTTOM,8);
set.connect(inflatedLayout.getId(),ConstraintSet.START,constraintLayout.getId(),ConstraintSet.START,8);
set.connect(inflatedLayout.getId(),ConstraintSet.END,constraintLayout.getId(),ConstraintSet.END,8);
set.connect(inflatedLayout.getId(),ConstraintSet.BOTTOM,swipeRefreshLayout.getId(),ConstraintSet.TOP,8);
set.applyTo(constraintLayout);
推荐阅读
- python-behave - 即使安装了“cucumber-tag-expressions 3.0.0”,带有“and”和“or”运算符的行为命令也不起作用
- python - 将 python pygame 转换为 exe 的问题
- c++ - decltype(std::get<0>(tup)) 到底是什么?
- python - 如何检查一个对象是否是某个 PyTorch 优化器?
- c - 使用 C 的 Skiplist 实现
- reactjs - 如何使用 Hooks 在 Reactjs 页面之间传递数据?
- html - 如何更改引导列的背景颜色
- r - 如何在 Jupyter lab .ipynb 文件中处理 R 内核 tibble 以显示有限的行结果?
- postgresql - 无法连接到位于 docker 容器中的数据库
- python - 在循环中根据 arr[i] 的值制作 python 列表的一部分