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

Explanation by lines of code:

13. binding — To get a layout containing ConstraintLayout.

Step 4: Add component onClick

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

OnClickListener | initListener | call initListener
Add Button

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

activiti_main | preview
btn | onClickListener

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
constraint_layout | activity_main
before | after

Step 7: Attaching a listener to external components

In activity_main add TextView:

TextView | preview
Button | preview
before | after




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