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

6

我有一个带有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个回答

4
replace 事务不会将当前视图从目标布局容器中移除,因此当您使用第一段代码时,新的 Fragment 被添加到了 contacts_layoutLinearLayout,但由于先前的视图占据了整个屏幕(高度),因此它不可见。
使用第二段代码,您向其中添加新的FragmentLinearLayout 是父级LinearLayout的第一个子元素,因此它有空间可以显示。
针对您要做的事情,我建议您将初始布局包装在一个 Fragment 类中,放置在一个包裹器布局中,您随后可以轻松地进行替换。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接