我有一个如下的观点:
<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
或任何其他约束属性的值,而无需在我的活动中再次设置整套属性?
答案 0 :(得分:9)
这是我做的(不需要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
答案 1 :(得分:6)
我刚刚在here找到答案,您可以使用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);
//you can do any other modification and then apply
constraintSet.applyTo( (ConstraintLayout) findViewById(R.id.activity_constraint));
答案 2 :(得分:3)
如果您使用的是Kotlin,并且拥有androidx-core-ktx lib,则只需执行以下操作:
someView.updateLayoutParams<ConstraintLayout.LayoutParams> { horizontalBias = 0.5f }
答案 3 :(得分:0)
免责声明:我还没有使用此特定功能。这只是我对如何尝试这样做的解释。
我认为你需要的是ConstraintSet
。获得后,您可以修改它并再次应用它。这是this article的相关示例。
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
}
}