繁体   English   中英

Android:以编程方式创建的布局动态添加到布局

[英]Android: Dynamically add a programmatically created layout to a layout

如何将动态创建的GridLayout添加到常规 XML LinearLayout 我已经找到了如何将常规 XML 布局添加到另一个布局的示例,但是在进行研究之后,我还没有找到有关动态创建的布局的示例。 下面是我的代码,我在其中动态创建了一个GridLayout ,我想将它添加到一个 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?

好吧,您可以以编程方式将任何组件添加到XML的“容器”,例如LinearLayour

例如:

科特林代码

您需要根据需要以编程方式创建组件(TextView、GridView、Edittext...)的第一个。

var _newEditText = EditText(activity)

然后是将此组件添加到layout container的代码

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

xml文件

<?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>

现在您可以对任何组件执行相同的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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