2014-10-09 52 views
0

我想创建一个自定义布局以减少代码中的冗余。目前每个布局文件都有大约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所有儿童应插入到第二线性-布局。我已经成功地这样做了。但我面对的布局问题(匹配父母不匹配的父母,只包)

我的做法是用下面的逻辑扩展的LinearLayout:

/** 
* 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_parent问题?

回答

0

在写这篇文章并努力思考如何最好地解释时,match_parent问题的解决方案变得清晰。尽管如果整个问题有更好的方法,问题仍然存在。

//Solution: 
this.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 

//wrong: 
this.addView(view); 
0

假设您有两个布局文件。 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>