Android: How to add Buttons to a Layout programmatically(with Buttons to be seen in the XML-View)

as the title states, i do want to add Buttons to a ConstraintLayout programmaticaly, whic implies, added Buttons are to be seen within the XML-File.

XML File:

<androidx.constraintlayout.widget.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"     tools:context=".MainActivity"     android:id="@+id/idMain">  </androidx.constraintlayout.widget.ConstraintLayout> 

Code for adding Buttons:

ConstraintLayout cst = (ConstraintLayout) findViewById(R.id.idMain); Button btn = new Button(this); btn.setText("Hallo Welt"); cst.addView(btn); 

Issue: Added Button is nowhere to be seen within the XML-File. Question: How to append the Button to the XML-File ?

UP

Add Comment
2 Answer(s)

try it:

ConstraintLayout cst = (ConstraintLayout)findViewById(R.id.idMain); ConstraintSet set = new ConstraintSet();  Button btn = new Button(this); // set view id, else getId() returns -1 btn.setId(View.generateViewId()); cst.addView(btn, 0);  set.clone(cst); set.connect(btn.getId(), ConstraintSet.TOP, cst.getId(), ConstraintSet.TOP, 60); set.applyTo(cst); 

How to programmatically add views and constraints to a ConstraintLayout?

Answered on July 17, 2020.
Add Comment

Use this code XML

    <android.support.constraint.ConstraintLayout          android:id="@+id/ly_id"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:layout_marginBottom="10dp"          android:layout_marginLeft="10dp"          android:layout_marginRight="10dp"          android:layout_marginTop="0dp">      </android.support.constraint.ConstraintLayout> 

Java code to add button programetically.

    ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.ly_id);      //set the properties for button     Button btnTag = new Button(this);     btnTag.setText("Button");     btnTag.setId(some_random_id);      //add button to the layout     layout.addView(btnTag); 
Answered on July 17, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.