首页 > 解决方案 > 如何以编程方式设置 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>

标签: javaandroidandroid-layout

解决方案


为了在运行时更改您的app:layout_constraintTop_toBottomOf属性RelativeLayout,您可以执行以下操作之一:

  1. 克隆 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。

  1. 修改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


推荐阅读