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
  • 6,990
  • 4
  • 32
  • 46
codeKiller
  • 4,984
  • 15
  • 53
  • 104
  • 1
    Check this out http://www.techotopia.com/index.php/Managing_Constraints_using_ConstraintSet – Kuls Sep 25 '17 at 08:43
  • thanks, it works well, maybe you want to make a short answer with a short example from that page so that I can accept it – codeKiller Sep 25 '17 at 08:50

1 Answers1

27

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
  • 1,987
  • 17
  • 38
  • 1
    thanks, I will accept the answer when it lets me do so – codeKiller Sep 25 '17 at 08:57
  • 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