如何以编程方式将 ConstraintLayout 添加到 LinearLayout [Android]

How to add a ConstraintLayout to a LinearLayout - programmaticaly [Android]

如标题所述,我有两个元素:

  1. 线性布局:

        <LinearLayout
             android:id="@+id/idContent"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             app:layout_constraintBottom_toBottomOf="parent"
             app:layout_constraintEnd_toEndOf="parent"
             app:layout_constraintHorizontal_bias="0.384"
             app:layout_constraintStart_toStartOf="parent"
             app:layout_constraintTop_toTopOf="parent"
             app:layout_constraintVertical_bias="0.419"
             android:orientation="horizontal">
    
         </LinearLayout>
    
  2. 约束布局

    <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"
     android:id="@+id/idExample">
    
      <EditText
             android:id="@+id/iddas"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:ems="10"
             android:inputType="date"
            />
     </androidx.constraintlayout.widget.ConstraintLayout>
    

问题:如何将ConstraintLayout添加到LinearLayout中?

我尝试了什么:

LinearLayout linear = (LinearLayout) findViewById(R.id.idContent);
ConstraintsLayout cst = (ConstraintsLayout) findViewById(R.id.idExample);
linear.addView(cst);

问题:错误:无法将空 child 视图添加到 ViewGroup

我猜是null因为它从来没有充气过。假设包含 ConstraintsLayout 的布局是 my_layout.xml,现在你应该先膨胀它,然后将它添加到 LinearLayout:

LayoutInflater layoutInflater = LayoutInflater.from(context);
View cst = layoutInflater.inflate(R.layout.my_layout, null);
linear.addView(cst);