0

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

1 Answers1

0

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);
Mr_vmh
  • 171
  • 1
  • 9