以编程方式添加约束

问题描述 投票:0回答:2

具有约束布局的布局定义中使用的以下 XML 指令的 java 代码翻译是什么?

app:layout_constraintBottom_toBottomOf="@+id/Button1"
app:layout_constraintTop_toTopOf="@+id/Button1"
app:layout_constraintLeft_toLeftOf="@+id/Button2"
app:layout_constraintRight_toRightOf="Button2"
android android-layout android-constraintlayout
2个回答
28
投票

这是一个以编程方式添加约束的示例,

ConstraintLayout mConstraintLayout  = (ConstraintLayout)fndViewById(R.id.mainConstraint);
ConstraintSet set = new ConstraintSet();

ImageView view = new ImageView(this);
mConstraintLayout.addView(view,0);
set.clone(mConstraintLayout);
set.connect(view.getId(), ConstraintSet.TOP, mConstraintLayout.getId(), ConstraintSet.TOP, 60);
set.applyTo(mConstraintLayout); 

了解更多详情可以参考约束布局


0
投票

也可以向以编程方式生成的视图添加约束,而无需创建新的约束集。这是 Kotlin 中的一个示例:

val tv = TextView(requireContext())
tv.text = "some text"
tv.layoutParams = ConstraintLayout.LayoutParams(
    ConstraintLayout.LayoutParams.WRAP_CONTENT,
    ConstraintLayout.LayoutParams.WRAP_CONTENT
).apply {
    topToTop = R.id.Button1
    bottomToBottom = R.id.Button1
    leftToLeft = R.id.Button2
    rightToRight = R.id.Button2
}
val layout = findViewById<ConstraintLayout>(R.id.myLayout)
layout.addView(tv)

将视图添加到布局后,修改布局参数也很容易:

tv.layoutParams = (tv.layoutParams as ConstraintLayout.LayoutParams).apply {
    topToTop = R.id.Button3
    bottomToBottom = R.id.Button3
}

只是不要忘记将修改后的布局参数重新分配给视图。否则更改将不会应用。

© www.soinside.com 2019 - 2024. All rights reserved.