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);
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.
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.
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.
You can use PARENT_ID
so your code becomes
params.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
params.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With