codeKiller
codeKiller

Reputation: 5758

Adding constraints programmatically

What is the translation to java code of the following XML instructions used in a layout definition with a constraint layout?

app:layout_constraintBottom_toBottomOf="@+id/Button1"
app:layout_constraintTop_toTopOf="@+id/Button1"
app:layout_constraintLeft_toLeftOf="@+id/Button2"
app:layout_constraintRight_toRightOf="Button2"

Upvotes: 14

Views: 15808

Answers (2)

Torben
Torben

Reputation: 6857

Adding constraints to a programmatically generated view is also possible without creating a new constraint set, but simply by just setting the layout parameters of the view. Here is an example in Kotlin and Java:

val tv = TextView(requireContext())
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)
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(
    ConstraintLayout.LayoutParams.WRAP_CONTENT,
    ConstraintLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.topToTop = R.id.Button1;
layoutParams.bottomToBottom = R.id.Button1;
layoutParams.leftToLeft = R.id.Button2;
layoutParams.rightToRight = R.id.Button2;

TextView tv = new TextView(requireContext());
tv.setLayoutParams(layoutParams);

ConstraintLayout layout = findViewById(R.id.myLayout);
layout.addView(tv);

It is also easy to modify the layout parameters after a view has already been added to a layout. Again an example in Kotlin and Java:

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

Just don't forget to re-assign the modified layout parameters to the view. Otherwise the changes won't be applied.

Upvotes: 0

Kuls
Kuls

Reputation: 2067

Here is an example of adding constraints programatically,

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); 

To know more details you can refer Constraint layout

Upvotes: 29

Related Questions