2014-10-09 54 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>