简体   繁体   中英

Android: Dynamically add a programmatically created layout to a layout

How do I add a dynamically created GridLayout to a regular XML LinearLayout ? I have found examples of how to add a regular XML layout to another layout, but after doing research, I haven't found an example with regards to dynamically created layouts. Below is my code, where I am dynamically creating a GridLayout and I want to add it to a layout with the id " difference_table ".

// Initialize the GridLayout for the difference table
var diffTable:GridLayout = GridLayout(this)

// How do I add this to R.id.difference_table?

Well you can add any component programmatically to a "container" in your XML like LinearLayour .

For example:

kotlin code

The first one you need to create the component (TextView, GridView, Edittext...) programmatically as you want.

var _newEditText = EditText(activity)

Then the code to add this component to your layout container

val rl = findViewById(R.id.layDynContainer) as LinearLayout
        rl.addView(_newEditText)

Xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <LinearLayout
            android:id="@+id/layDynContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:layout_marginBottom="16dp"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>
    </androidx.core.widget.NestedScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

Now you can do the same for any component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM