ConstraintLayout: Adding components programmatically.

Step by step adding a component to ConstraintLayout.

Programmatically adding components to ConstraintLayout

What should happen:

Perform step by step:

Step 1: Project creation

Сreate EmptyProject with root ConstraintLayout (id = constraint_layout):

EmptyProject | root ConstraintLayout

Step 2: Component creation

In folder app -> res -> layout create a file button (tools: works only for preview), and in this file create a button:

Path | Button | Preview

Step 3: The concept of programmatically adding components to the ConstraintLayout

Open MainActivity and create a method for adding components UI to ConstraintLayout:

Explanation by lines of code:

13. binding — To get a layout containing ConstraintLayout.

16. increment — To change id.

18. lastID — To get the last id.

30. layout — To get ConstraintLayout to which will be added components UI.

31. button — To get Button to be added to ConstraintLayout.

33. — To change id.

35. addView — to add a component.

37. set — initialization ConstraintSet.

38. clone — clone the current layout.

39. also — we use a short name instead of a long name.

40. connect — constrain the component. (1 param — who to attach,

2 param — which side to attach, 3 param — to whom to attach, 4 patam -which side to attach).

41. if — attach the first component to the top.

43. else — to attach other components to the previous ones.

48. applyTo — apply modified layout.

Step 4: Add component onClick

Add View.OnClickListener, create a listener initialization method and add it to onClick:

OnClickListener | initListener | call initListener

Create a method:

Add Button

Implement onClick:


Run the application:


Step 5: Adding a component when clicking on an existing component

Add a button to activity_main:

activiti_main | preview

Attach a listener to a button:

btn | onClickListener

Run the application:


Step 6: Solving the problem of losing restrictions by parent components

SOLUTION — components will be added not to the parent ConstreintLayout but to the external:

In folder app -> res -> layout create a file constraint_layout:

Path | constraint_layout

Include constraint_layout in activity_main:

constraint_layout | activity_main

Slightly change the method of adding components:

before | after

Run the application:


Step 7: Attaching a listener to external components

In activity_main add TextView:

TextView | preview

Change activity_main:

Button | preview

Change increment:


Slightly change the method of adding components:

before | after

Run the application:



If you have any questions, you can ask them personally to Me at Twitter.



LibGDX | Android | Developer | DragonBones | Enthusiast.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store