Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 927
Ehsan Avatar asked Apr 16 '17 18:04

Ehsan


People also ask

What is parent ConstraintLayout?

We give that ConstraintLayout a height and width of match_parent , which indicates that this widget or container should fill up the available space of its parent container. In this case, the “parent” is a container that occupies most of the space on the screen, so the ConstraintLayout will fill that space.

Is ConstraintLayout faster than LinearLayout?

More complex layout but results are the same, flat Constraint Layout is slower than nested Linear Layout. I want to pay attention to 2 more things which are more subjective. Creating Constraint Layout takes more time than other layouts. Also introducing changes in existing Constraint Layout is much more time-consuming.

Can we use LinearLayout in ConstraintLayout?

Most of what can be done in LinearLayout and RelativeLayout can now be done with a new layout system called ConstraintLayout. It's important to note the class hierarchy of these View Layouts.


2 Answers

You can use PARENT_ID

so your code becomes

params.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
params.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
like image 123
Stephen Avatar answered Oct 20 '22 23:10

Stephen


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.

like image 37
S Haque Avatar answered Oct 20 '22 22:10

S Haque