简体   繁体   中英

How to insert a layout into another frameLayout?

I am trying to insert a resource layout into a frame layout but failed. The frame layout is in activity_main.xml

My frame layout is (frame_result_contact.xml):

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frame"
    app:layout_constraintTop_toTopOf="parent"/>

The layout I'm trying to insert is:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="350dp"
    android:orientation="vertical">

    <ImageView
        android:layout_margin="10dp"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:src="@drawable/ic_user"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textSize="34sp"
        android:textAlignment="center"
        android:id="@+id/contact_name"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textSize="24sp"
        android:textAlignment="center"
        android:id="@+id/contact_info"
        android:layout_gravity="center"/>

</LinearLayout>

</androidx.cardview.widget.CardView>

and my code is:

LayoutInflater inflater = (LayoutInflater) Objects.requireNonNull(getActivity()).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view  = inflater.inflate(R.layout.frame_result_contact,frame,true);
        frame.addView(view);

And this is my error code:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

I just don't understand what's the parent of the child? How to insert that layout into the frame layout?

Try replacing this: View view = inflater.inflate(R.layout.frame_result_contact,frame,true);

With this: View view = inflater.inflate(R.layout.frame_result_contact,frame,false);

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