How to Programmatically add Views to ConstraintLayout in Android

In this android programming source code example, we are going to explore how to add Views programmatically in ConstraintLayout in Android.

Below is a step by step source code to add Views programmatically in ConstraintLayout in Android.

activity_layout20.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/constraintLayout"
    tools:context=".layout.Layout20">

</android.support.constraint.ConstraintLayout>

Layout20.java

import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import com.inducesmile.inducesmile_button.R;

public class Layout20 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout20);

        ConstraintLayout constraintLayout = (ConstraintLayout)findViewById(R.id.constraintLayout);

        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.notebook);

        constraintLayout.addView(imageView, 0);
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment