重新使用Android布局

时间:2012-06-14 14:40:24

标签: android android-layout

我有一个root_layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/background"
android:weightSum="10">

    <FrameLayout
        android:id="@+id/parentViewHolder"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="8"
        android:background="@android:color/transparent"
        android:cacheColorHint="@android:color/transparent" >
    </FrameLayout>

    <TextView
        android:id="@+id/spaceHolder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="TEXT">
    </TextView>

现在我希望,每当我想要更改屏幕时,使用这些布局并填充其他声明的layout.xml

我尝试使用

    protected void Setup(int _layoutResourceId) 
{ 
    layoutResourceId = _layoutResourceId;
    FrameLayout holder = (FrameLayout) activity.findViewById(R.id.parentViewHolder);

    LayoutInflater layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
    holder.addView(layoutInflater.inflate(layoutResourceId, null, false)); 
    activity.screen = this;
}

但这没有用。没有人知道更好的实施吗?

3 个答案:

答案 0 :(得分:1)

您可以重复使用这样的布局:

首先,实现问题中描述的布局。例如,它的文件名是root_layout.xml。

然后,如果您想在另一个视图中使用它,只需将其添加到您的xml文件中:

<include layout="@layout/root_layout"></include>

root_layout将被扩充到另一个布局。

请注意,root_layout的每个属性都会被保留。所以要注意它们。

答案 1 :(得分:1)

你没有说它是如何工作的,所以我假设你在屏幕上留下了两个观点......你应该使用removeAllViews()

试试这个:

protected void Setup(int _layoutResourceId)  
{  
    layoutResourceId = _layoutResourceId; 
    FrameLayout holder = (FrameLayout) activity.findViewById(R.id.parentViewHolder); 
    holder.removeAllViews();  
    LayoutInflater layoutInflater = (LayoutInflater)activity.getSystemService (Context.LAYOUT_INFLATER_SERVICE);     
    holder.addView(layoutInflater.inflate(layoutResourceId, null, false));  
    activity.screen = this; 
} 

答案 2 :(得分:1)

如果您要从发布的布局中为FrameLayout添加不同的布局,请按以下步骤操作:

protected void Setup(int _layoutResourceId) { 
    layoutResourceId = _layoutResourceId;
    FrameLayout holder = (FrameLayout) activity.findViewById(R.id.parentViewHolder);
    holder.removeAllViews();
    LayoutInflater layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
    layoutInflater.inflate(layoutResourceId, holder, true)); 
    activity.screen = this;
}