title: Creating Android ConstraintLayout and Guidelines in code
body: <p>How do you create ConstraintLayouts and Guidelines programmatically? I've tried the below code to create a simple layout that anchors a view to the middle of the screen using a Guideline, but it renders the red 'v' view on the left side of the screen (see <a href="https://i.stack.imgur.com/8bIos.png" rel="nofollow noreferrer">screenshot</a>)</p>
  
  <pre><code>public class MainActivity extends Activity {
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
  
          ConstraintLayout cl = new ConstraintLayout(this);
          cl.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
          setContentView(cl);
  
          Guideline gl = new Guideline(this);
          ConstraintLayout.LayoutParams gllp = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 500);
          gllp.guidePercent = 0.5f;
          gllp.orientation = LinearLayout.VERTICAL;
          gl.setLayoutParams(gllp);
          gl.setId(View.generateViewId());
          cl.addView(gl);
  
          View v = new View(this);
          v.setId(View.generateViewId());
          v.setBackgroundColor(0xFFFF0000);
          ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(50, 500);
          lp.rightToRight = gl.getId();
          v.setLayoutParams(lp);
          cl.addView(v);
      }
  }
  </code></pre>