简体   繁体   中英

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

as the title states, i do have two Elements:

  1. LinearLayout:

     <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. ConstraintsLayout

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

Quesiton : How to add the ConstraintLayout to the LinearLayout?

What i tried:

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

Issue: Error: Cannot add a null child view to a ViewGroup

I guess it is null because it has never been inflated. Assume the layout that contains the ConstraintsLayout is my_layout.xml , now you should inflate it first, then add it to the LinearLayout :

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

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