ConstraintLayout以编程方式

时间:2017-04-19 11:09:21

标签: android android-constraintlayout

我正在尝试以编程方式向ConstraintLayout添加视图。问题在于ConstraintLayout.LayoutParams忽略MATCH_CONSTRAINT和我的观点,而不是让最大宽度居中。

    TextView textView = new TextView(context);

    ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(MATCH_CONSTRAINT, WRAP_CONTENT);
    lp.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
    lp.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
    lp.rightToLeft = guideline.getId();
    lp.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;

    textView.setLayoutParams(lp);
    textView.setText("Title text");
    textView.setBackgroundColor(Color.BLUE);

    constraintLayout.addView(textView);

1 个答案:

答案 0 :(得分:4)

textView = new TextView(this);
textView.setId(R.id.text_id);
ConstraintSet set = new ConstraintSet();
set.clone(constraintLayout);
set.connect(textView.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
set.connect(textView.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0);
set.connect(textView.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 0);
set.connect(textView.getId(), ConstraintSet.RIGHT, guideline.getId(), ConstraintSet.LEFT, 0);
textView.setText("Title text");
textView.setBackgroundColor(Color.BLUE);

constraintLayout.addView(textView);
set.applyTo(constraintLayout);

ID的Xml值

<item name="text_id" type="id"/>