java - 如何以编程方式设置 RelativeLayout 的 layout_constraintTop_toBottomOf “父级”?(安卓)
问题描述
我想app:layout_constraintTop_toBottomOf
在运行时更改元素的。我试图用这个问题/答案来解决它:
Android:如何以编程方式设置 layout_constraintRight_toRightOf “parent”
不幸的是,我的元素是 a RelativeLayout
,所以它不能被强制转换为ConstraintLayout
,就像在这个带有约束集的答案中一样
然后我尝试根据这个答案使用 LayoutParams解决它,但RelativeLayout.LayoutParams
没有像toBottomOf
.
布局如下所示:
<RelativeLayout
android:id="@+id/myElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/otherElement">
<!-- Child elements -->
</RelativeLayout>
解决方案
为了在运行时更改您的app:layout_constraintTop_toBottomOf
属性RelativeLayout
,您可以执行以下操作之一:
- 克隆 ConstraintLayout 的 ConstraintSet,即您的 RelativeLayout 的父视图。更新克隆的 ConstraintSet 中的约束,然后将 ConstraintSet 应用回 ConstraintLayout。
示例代码:
//ConstraintLayout constraintLayout = findViewById<View>(R.id.myElement).getParent()
constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
constraintSet.connect(R.id.myElement, ConstraintSet.TOP, [other element Id], ConstraintSet.BOTTOM);
constraintSet.applyTo(constraintLayout);
请注意:您应该将 ConstraintLayout 传递给 ConstraintSet.clone() 方法,而不是 RelativeLayout。
- 修改LayoutParams的
myElement
视图!
像那样:
//RelativeLayout myElement = findViewById<RelativeLayout>(R.id.myElement)
LayoutParams layoutParams = (LayoutParams) myElement.getLayoutParams();
layoutParams.topToBottom = [id of the another view];
myElement.setLayoutParams(layoutParams);
myElement
在这种情况下,如果is的父级,ConstraintLayout
您将获得myElement.getLayoutParams();
具有 property的 ConstraintLayout.LayoutParams 类topToBottom
。
推荐阅读
- c++ - 为什么 int arr[]={0,3,2,4,5,6,7}; 给出错误和 int arr[7]={0,3,2,4,5,6,7}; 不是
- .net-core - 读取 dotnet core 上的用户配置文件相关文件
- objective-c - iOS - 无法将 .MOV 和 .jpg 保存为 LivePhoto - 显示错误 NSCocoaErrorDomain Code=-1 [目标 C]
- docker - 为什么没有在 docker swarm 中运行的 kafka 端口?
- reactjs - 如何在渲染中调用方法而不是componentDidUpdate?
- android - 如何安全退出 Android Camera2BasicFragment 并在下一个活动中显示捕获的图像?
- scala - Spark小数类型精度损失
- python - 从 azure blob 存储中读取多行
- php - 如果发现日期字符串在日期之间,则返回 pay_period_start 和 pay_period_end。如何?
- python - 用于 Win32 平台的 CMake find_package(PythonInterp 3.7 REQUIRED)