14

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"
Somesh Kumar
  • 8,088
  • 4
  • 33
  • 49
codeKiller
  • 5,493
  • 17
  • 60
  • 115
  • 1
    Check this out http://www.techotopia.com/index.php/Managing_Constraints_using_ConstraintSet – Kuls Sep 25 '17 at 08:43

1 Answers1

28

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

Kuls
  • 2,047
  • 21
  • 39
  • 1
    When i add view according to above answer and remove button and reset constraints as according to xml i`m having the exception "All children of ConstraintLayout must have ids to use ConstraintSet" – Asad Mukhtar Sep 05 '19 at 06:42
  • 1
    @AsadMukhtar you might need to add an ID to your view then. In the example above, the ImageView ID can be set with `view.id = View.generateViewId()`. – Big McLargeHuge Mar 20 '20 at 14:35
  • Thanks but i fixed it by declaring id as attribute in attrs file – Asad Mukhtar Mar 20 '20 at 21:34