snoob
snoob

Reputation: 11

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

Upvotes: 1

Views: 2402

Answers (2)

snoob
snoob

Reputation: 11

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.

Upvotes: 0

Nicolas Roard
Nicolas Roard

Reputation: 8449

Which version of ConstraintLayout are you using? Trying your example with beta 3, I get the correct behavior:

enter image description here

edit -- I was incorrect, and beta 4 has the fix for this issue.

In addition, for programmatically creating layout params with ConstraintLayout, you should call the validate() function on ConstraintLayout.LayoutParams before setting it to the view.

Upvotes: 2

Related Questions