Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Constraint Layout Programmatically?

In iOS I'm a big fan of deleting the storyboard and using the Cartography framework to lay everything out in code. This is stolen from Cartography's github:

constrain(view1, view2) { view1, view2 in     view1.width   == (view1.superview!.width - 50) * 0.5     view2.width   == view1.width - 50     view1.height  == 40     view2.height  == view1.height     view1.centerX == view1.superview!.centerX     view2.centerX == view1.centerX      view1.top >= view1.superview!.top + 20     view2.top == view1.bottom + 20 } 

Is there any equivalent at all for Android? It seems like the new Constraint Layout is a step in the right direction but I would like to do it programmatically.

like image 247
sheldon.parkes Avatar asked Sep 02 '16 16:09

sheldon.parkes


People also ask

What is Android constraint layout?

A ConstraintLayout is a ViewGroup which allows you to position and size widgets in a flexible way. Note: ConstraintLayout is available as a support library that you can use on Android systems starting with API level 9 (Gingerbread). As such, we are planning on enriching its API and capabilities over time.


1 Answers

A little late to the game, but you need to basically treat your views in a constraint layout as regular views that simply have their own LayoutParams.

In the ConstraintLayout case, the documentation is located here: https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout.LayoutParams

This class contains the different attributes specifying how a view want to be laid out inside a ConstraintLayout. For building up constraints at run time, using ConstraintSet is recommended.

So, the recommended method is to use a ConstraintSet.

There's a nice code sample there, but the core concept is you need to create a new set (by copying/cloning/new, etc), set its properties, and then apply it to your layout.

E.g.: Suppose your layout contains a ConstraintLayout (called mConstraintLayout here) and inside it contains a view (R.id.go_button in the sample), you could do:

    ConstraintSet set = new ConstraintSet();      // You may want (optional) to start with the existing constraint,     // so uncomment this.     // set.clone(mConstraintLayout);       // Resize to 100dp     set.constrainHeight(R.id.go_button, (int)(100 * density));     set.constrainWidth(R.id.go_button, (int)(100 * density));      // center horizontally in the container     set.centerHorizontally(R.id.go_button, R.id.rootLayout);      // pin to the bottom of the container     set.connect(R.id.go_button, BOTTOM, R.id.rootLayout, BOTTOM, 8);      // Apply the changes     set.applyTo(mConstraintLayout);      // this is my… (ConstraintLayout) findViewById(R.id.rootLayout); 
like image 51
Martin Marconcini Avatar answered Sep 25 '22 04:09

Martin Marconcini