在约束布局中以编程方式向视图添加约束

时间:2019-07-10 15:49:17

标签: android android-constraintlayout

我正在以编程方式创建TextView,并将其添加到约束布局中。默认情况下,它们位于左上角。我希望它们彼此下方,第一个位于EditText下方。

这是我的代码:

ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.cLayout);
ConstraintSet set = new ConstraintSet();
TextView tv = new TextView(this);
ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(
    ConstraintLayout.LayoutParams.WRAP_CONTENT, // Width of TextView
    ConstraintLayout.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
set.clone(layout);
set.connect(tv.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 8);
set.connect(tv.getId(), ConstraintSet.TOP, editText.getId(), ConstraintSet.BOTTOM, 8);
tv.setId(View.generateViewId());
set.applyTo(layout);
layout.addView(tv,0);

如您所见,我已经从View的TOP到editText的BOTTOM设置了一个约束。仍然显示在左上角。为什么会这样?

1 个答案:

答案 0 :(得分:0)

您的代码顺序不正确,以下代码应该可用。

ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.cLayout);

TextView tv = new TextView(this);
tv.setText("Something");
tv.setId(View.generateViewId());
ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(
    ConstraintLayout.LayoutParams.WRAP_CONTENT, // Width of TextView
    ConstraintLayout.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
layout.addView(tv,0);

ConstraintSet set = new ConstraintSet();
set.clone(layout);
set.connect(tv.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 8);
set.connect(tv.getId(), ConstraintSet.TOP, editText.getId(), ConstraintSet.BOTTOM, 8);
set.applyTo(layout);

PS-我同意Syed Ahmed Jamil的观点,您最好使用RecyclerViewListView,但是知道如何正确设置ConstraintLayout约束也无济于事。