在Constraint Layout中添加视图并将其全屏设置为PROGRAMMATICALLY

时间:2017-09-12 02:16:40

标签: android layout constraints fullscreen programmatically

我花了几个小时在ConstraintLayout中添加一个imageview并将其设置为全屏大小。

这是我在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);

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

问题是您没有为图像视图设置宽度和高度,因此默认情况下会同时使用wrap_content。因此将它们设置为0dp将解决问题。添加这些行以将宽度和高度设置为0dp。

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

还有一件事,您可以使用ConstraintSet.PARENT_ID,而不是将父ID作为constraintLayout.getId()。所以最终的代码看起来像

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

希望这会有所帮助