Как изменить макет ограничения программно?
У меня есть вид, как показано ниже:
<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
или какое-либо другое свойство ограничения программно, без того, чтобы снова установить весь набор свойств снова в моей деятельности?
3 ответа
Я только что нашел ответ здесь, и вы можете использовать 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));
Вот что я сделал (не нужно 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
"s OnSeekBarChangeListener
Если вы используете Kotlin и у вас есть библиотека androidx-core-ktx, вы можете просто сделать:
someView.updateLayoutParams<ConstraintLayout.LayoutParams> { horizontalBias = 0.5f }
Отказ от ответственности: я не использовал эту конкретную функциональность. Это просто моя интерпретация того, как я буду пытаться это сделать.
Я думаю, что вам нужно 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
}
}