0

我已经扩展了 ConstraintLayout 并以编程方式添加视图,然后为每个视图设置约束。但有些如何它不起作用,只显示第一个视图。无法弄清楚我哪里出错了。

addViews(){
        titleInfoView = new TextView(getContext());
        titleInfoView.setId(ViewCompat.generateViewId());
        addView(titleInfoView);

        editBoxView = new EditText(contextWrapper);
        editBoxView.setId(ViewCompat.generateViewId());
        addView(editBoxView);

        notInfoView = new TextView(getContext());
        notInfoView.setId(ViewCompat.generateViewId());
        addView(notInfoView);
    
        errorMessageView = new TextView(getContext());
        errorMessageView.setId(ViewCompat.generateViewId());
        addView(errorMessageView);

}

然后为每个视图添加约束

 private void addConstraintToViews() {
     
        ConstraintSet set = new ConstraintSet();
        set.clone(this);

        //connect title view
        set.connect(titleInfoView.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP);
        set.connect(titleInfoView.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
        set.connect(titleInfoView.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);


        //connect edit box
        set.connect(editBoxView.getId(), ConstraintSet.TOP, titleInfoView.getId(), ConstraintSet.BOTTOM, R.dimen.margin_10);
        set.connect(editBoxView.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
        set.connect(editBoxView.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);

        //connect info title
        set.connect(notInfoView.getId(), ConstraintSet.TOP, editBoxView.getId(), ConstraintSet.BOTTOM, R.dimen.margin_10);
        set.connect(notInfoView.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
        set.connect(notInfoView.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);

        //connect error messag
        set.connect(errorMessageView.getId(), ConstraintSet.TOP, notInfoView.getId(), ConstraintSet.BOTTOM, R.dimen.margin_10);
        set.connect(errorMessageView.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
        set.connect(errorMessageView.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
        set.connect(errorMessageView.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);

        set.applyTo(this);
    }

只有第一个项目出现,即像这张图片一样的标题。我想一个接一个地添加每个视图,以及我是如何编写约束集的。任何人都可以提出问题所在。 在此处输入图像描述

4

1 回答 1

0

我终于弄清楚了这个问题。我为每个小部件正确设置了布局参数,但是当我在父约束布局下为每个小部件设置约束时,我在最后添加了边距。

这似乎是个问题,可能是约束布局上的一些错误。刚刚删除了该边距,现在显示视图。

于 2020-09-01T11:16:14.553 回答