Ehsan
Ehsan

Reputation: 2781

How to access parent in ConstraintLayout

I am using ConstraintLayout to create a view programmatically and I want to set my button view topTotop of parent and leftToleft of the parent. How can I do that?

My code is below:

Button button = new Button(MainActivity.this);
ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(widthInt, heightInt);

params.topToTop =  // I want to set it parent
params.leftToLeft = // I want to set it parent
params.setMargins(marginStartint , marginTopInt , 0 , 0);
button.setLayoutParams(params);

Upvotes: 12

Views: 7519

Answers (2)

Stephen
Stephen

Reputation: 4249

You can use PARENT_ID

so your code becomes

params.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
params.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;

Upvotes: 28

S Haque
S Haque

Reputation: 7281

You can use ConstraintSet's Connect method to perform such operations. There PARENT_ID to refer parent id.

ConstraintLayout layout = (ConstraintLayout)fndViewById(R.id.mainConstraint);
ConstraintSet set = new ConstraintSet();
set.clone(layout);
set.connect(view.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
//view refers to the view's constraint to be changed
set.applyTo(layout);

connect

void connect (int startID, int startSide, int endID, int endSide, int margin)

Create a constraint between two widgets.

Upvotes: 2

Related Questions