Android 复合布局

Android 复合布局,android,android-layout,Android,Android Layout,我想创建一个自定义布局,以减少代码中的冗余。目前,每个布局文件都有大约30行相同的代码 我的目标是创建一个自定义布局/视图,它本身可以容纳子对象 <BaseLayout xmlns:...> <!-- Normal Content --> <Button /> <Label /> </BaseLayout> 虽然上面的xml包含大部分内容,但BaseLayout本身是一个包含其他视图和功能的xml: <Fr

我想创建一个自定义布局,以减少代码中的冗余。目前,每个布局文件都有大约30行相同的代码

我的目标是创建一个自定义布局/视图,它本身可以容纳子对象

<BaseLayout xmlns:...>
   <!-- Normal Content -->
   <Button /> 
   <Label /> 
</BaseLayout>
虽然上面的xml包含大部分内容,但BaseLayout本身是一个包含其他视图和功能的xml:

<FrameLayout xmlns:...>
   <LinearLayout><!-- contains the Header--></LinearLayout>

   <LinearLayout><!-- INDIVIDUAL CONTENT HERE--></LinearLayout>

   <FrameLayout><!-- contains the loading screen overlay --></FrameLayout>
</FrameLayout>
因此,上述xml中的所有子项都应该插入到第二个线性布局中。我已经成功地做到了这一点。但我遇到了布局问题,匹配父对象不匹配父对象,而只进行包装

我的方法是用以下逻辑扩展线性布局:

/**
 * extracting all children and adding them to the inflated base-layout
 */
@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    View view = LayoutInflater.from(getContext()).inflate(R.layout.base_layout, null);

    LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.base_layout_children);
    while(0 < getChildCount())
    {
        View child = getChildAt(0);
        LinearLayout.MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();
        removeViewAt(0);
        linearLayout.addView(child, layoutParams);
    }
    this.addView(view);
}
是否有更好、更干净的方法封装xml并重用基本布局?如何解决match\u家长问题?

在写这篇文章并认真思考如何最好地解释时,match\u家长问题的解决方案变得清晰起来。尽管问题仍然存在,是否有更好的方法解决整个问题


假设您有两个布局文件。common_views.xml和layout_main.xml。可以像这样将一个布局文件的内容包含到另一个布局文件中

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

        <include
            android:id="@+id/common"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"                
            layout="@layout/common_views" />

        <WebView
            android:id="@+id/webView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@+id/common"
           >
        </WebView>

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

        <include
            android:id="@+id/common"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"                
            layout="@layout/common_views" />

        <WebView
            android:id="@+id/webView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@+id/common"
           >
        </WebView>

    </RelativeLayout>