snoob snoob - 17 days ago 11
Android Question

Creating Android ConstraintLayout and Guidelines in code

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

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

Answer

This was a bug that is now fixed in beta4. Note that you have to call lp.validate() after setting up ConstraintLayout.LayoutParams in code. More details at https://code.google.com/p/android/issues/detail?id=227039.

Comments