动态地将布局包含到片段内的另一个布局文件中

Amr*_*Saj 1 android include fragment android-layout android-fragments

我有一个片段布局,我想动态添加另一个子布局,

我试过这个/sf/answers/1581458861/

子布局xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:hint="Question"
    android:textColor="@color/colorTextBlack"
    android:textSize="16dp" />
</android.support.constraint.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

这是我的主要布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:orientation="vertical">
<FrameLayout
    android:id="@+id/flContainer"
    android:layout_width="match_parent"
    android:layout_margin="20dp"
    android:layout_height="wrap_content"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

在我的片段中我包含了子布局

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_start_question, container, false);
     flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
     flContainer.addView(R.layout.sub_layout);
    return v;
}
Run Code Online (Sandbox Code Playgroud)

但我在addView附近收到错误截图如下 在此输入图像描述

任何人都可以帮助找到错误

Nil*_*hod 7

您正在获取错误,因为 addView(View child)需要参数a view并且您正在添加FrameLayout哪个是ViewGroup

试试这种方式

LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View myView = inflater.inflate(R.layout.sub_layout, null);;
flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
flContainer.addView(myView);
Run Code Online (Sandbox Code Playgroud)