Search code examples
androidlayoutconstraintsfullscreen

Add views inside Constraint Layout and set them full screen programmatically


I spent some hours adding a imageview inside a ConstraintLayout and setting it to fullscreen size.

This is my actual code for add the image inside the Constraint Layout:

final ConstraintLayout constraitLayout = (ConstraintLayout)activity.findViewById(layout_xml);
    constraitLayout.addView(mImage,0);
    ConstraintSet set1 = new ConstraintSet();
    set1.clone(constraitLayout);
    set1.connect(mImage.getId(), ConstraintSet.TOP, constraitLayout.getId(), ConstraintSet.TOP, 0);
    set1.connect(mImage.getId(), ConstraintSet.LEFT, constraitLayout.getId(), ConstraintSet.LEFT, 0);
    set1.connect(mImage.getId(), ConstraintSet.RIGHT, constraitLayout.getId(), ConstraintSet.RIGHT, 0);
    set1.connect(mImage.getId(), ConstraintSet.BOTTOM, constraitLayout.getId(), ConstraintSet.BOTTOM, 0);
    set1.applyTo(constraitLayout);

Thanks for help!


Solution

  • the issue is you didn't set width and height to your image view so by default wrap_content is taken for both. So setting them both 0dp will fix the issue . Add these lines to set the width and height to 0dp.

     mImage.setLayoutParams(
                new LinearLayoutCompat.LayoutParams(
                        0,0));
    

    One more thing , instead of getting parent id as constraintLayout.getId() you can use ConstraintSet.PARENT_ID. So final code looks like

     mImage.setLayoutParams(
                new LinearLayoutCompat.LayoutParams(
                        0,0));
        constraitLayout.addView(mImage,0);
        ConstraintSet set1 = new ConstraintSet();
        set1.clone(constraitLayout);
        set1.connect(mImage.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
        set1.connect(mImage.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 0);
        set1.connect(mImage.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
        set1.connect(mImage.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0);
        set1.applyTo(constraitLayout);
    

    hope this helps