我想創建一個自定義佈局以減少代碼中的冗餘。目前每個佈局文件都有大約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問題?