Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConstraintLayout programmatically

I'm trying to add view to ConstraintLayout programmatically. The problem in that that ConstraintLayout.LayoutParams ignore MATCH_CONSTRAINT and my view instead of getting max width just centered.

    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);
like image 946
Near1999 Avatar asked Apr 19 '17 11:04

Near1999


1 Answers

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

Xml Value for ID

<item name="text_id" type="id"/>
like image 149
S Haque Avatar answered Oct 06 '22 23:10

S Haque