替换父片段根布局的子片段

时间:2013-04-19 14:51:10

标签: android android-fragments android-viewpager

我有一个包含5个片段的viewpager,其中一个我希望通过按钮点击完全替换它。我也希望能够通过后退按钮隐藏子片段。 这里是片段布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/contacts_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@null">
<LinearLayout
    android:id="@+id/import_contacts"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

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

<Button
    android:id="@+id/btn_my_clusters"
    android:background="@drawable/btn_wide_arrow_bg"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/TEXT"
    android:text="@string/btn_my_clusters_text"
    android:layout_marginBottom="10dp"/>

<ProgressBar
    android:id="@+id/progress_bar"
    android:layout_height="fill_parent"
    android:layout_width="wrap_content"
    android:layout_gravity="center"/>

<ListView
    android:id="@+id/contacts_list"
    android:divider="@null"
    android:listSelector="@android:color/transparent"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"/>
</LinearLayout>

当我尝试像这样替换contacts_layout时:

ImportContactsFragment importContactsFragment = new  ImportContactsFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.contacts_layout, importContactsFragment).commit();

它不起作用(我的意思是没有错误,但我的ImportContactsFragment根本没有显示)。但是当我尝试像这样替换import_contacts视图时:

ImportContactsFragment importContactsFragment = new  ImportContactsFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.import_contacts, importContactsFragment).commit();

一切正常,显示了ImportContactsFragment。

所以我想知道是否有可能用子片段替换所有片段内容?也许我可以用其他方式做到这一点?

1 个答案:

答案 0 :(得分:4)

replace事务不会从目标布局容器中删除当前视图,因此当您使用第一批代码时,新的Fragment会添加到contacts_layout LinearLayout,但它将不会被视为以前的视图覆盖整个屏幕(高度)。

使用第二段代码,您添加新LinearLayout的{​​{1}}是父Fragment的第一个子项,并且它有空格,因此可见。

对于你正在做的事情,我建议你将初始布局包装在一个放置在包装器布局中的LinearLayout类中,然后你可以很容易地替换它。

相关问题