如何以编程方式修改约束布局?



我得到了如下视图:

<org.rayanmehr.atlas.shared.customview.CustomTextView
android:id="@+id/tvDownVoteCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
app:layout_constraintVertical_bias="0"
app:layout_constraintTop_toBottomOf="@+id/anchorHelper"
app:layout_constraintLeft_toRightOf="@+id/tvDownVoteIcon"
app:layout_constraintBottom_toBottomOf="@+id/imgComment"
/>

如何以编程方式修改app:layout_constraintVertical_bias或任何其他约束属性的值,而无需在我的活动中再次设置 top 整组属性?

这是我所做的(不需要ConstraintSet,我们可以直接处理约束本身):

ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) myView.getLayoutParams();
params.horizontalBias = 0.2f; // here is one modification for example. modify anything else you want :)
myView.setLayoutParams(params); // request the view to use the new modified params

当我有一个SeekBar和它下面的TextView(左+右对齐)时,它就像一个魅力,我想更新TextView位置以在SeekBar的光标下,所以我不得不更新SeekBar上的水平偏置参数OnSeekBarChangeListener

如果您使用的是 Kotlin,并且您有 androidx-core-ktx lib,您可以简单地执行以下操作:

someView.updateLayoutParams<ConstraintLayout.LayoutParams> { horizontalBias = 0.5f }

我刚刚在这里找到了答案,您可以使用ConstraintSet来实现这一点,如下所示:

ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(context, R.id.activity_constraint);
//for example lets change the vertical bias of tvDownVoteIcon
float biasedValue = 0.2f;
constraintSet.setVerticalBias(R.id.tvDownVoteIcon, biasedValue);
//or change the anchor
constraintSet.connect
(R.id.tvDownVoteIcon,ConstraintSet.RIGHT,R.id.txt,ConstraintSet.RIGHT,0);
//then apply
constraintSet.applyTo( (ConstraintLayout) findViewById(R.id.activity_constraint));

免责声明:我没有使用过这个特定的功能。这只是我对如何尝试这样做的解释。

我认为你需要的是ConstraintSet.获得它后,您可以修改它并再次应用它。这是本文中的一个相关示例。

override fun onCreate(savedInstanceState: Bundle?) {
...
val constraintSet1 = ConstraintSet()
constraintSet1.clone(constraintLayout)
val constraintSet2 = ConstraintSet()
constraintSet2.clone(constraintLayout)
constraintSet2.centerVertically(R.id.image, 0)
var changed = false
findViewById(R.id.button).setOnClickListener {
TransitionManager.beginDelayedTransition(constraintLayout)
val constraint = if (changed) constraintSet1 else constraintSet2
constraint.applyTo(constraintLayout)
changed = !changed
}
}

最新更新