我认为您可能误解了我的评论,因此我将在这里提供更详细的解释。
删除或替换片段时经常出现的一个问题是尝试删除通过 XML(而不是在 Java 中以编程方式)添加到布局的片段。这是not与在中扩展片段自己的布局相同onCreateView()
片段的 Java 代码的函数(这似乎是您在对我的评论的回复中描述的内容)。为了说明我正在谈论的内容,我将向您展示人们尝试删除/替换片段的两种方法。
这是错误的做法:
XML 布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.ExampleFragment"
android:id="@+id/example_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Java:
swapFragment()
{
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
该代码不会按照您期望的方式执行。添加到 XML 布局中的初始片段不会被删除。这是因为 XML 布局旨在描述静态布局元素。您可以在运行时更改它们的内容,或隐藏它们,但无法从布局中删除这些内容。这就是黛安·哈克伯恩 (Dianne Hackborn) 在讨论话题 http://groups.google.com/group/android-developers/browse_thread/thread/b56967e0f147168d?pli=1我之前链接过。
这是正确的方法(至少根据我的经验):
XML 布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Fragment will go here eventually, but it's not added in the layout -->
</LinearLayout>
Java:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
ExampleFragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, newFragment);
transaction.commit();
}
...
swapFragment()
{
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
该策略不会在初始布局中添加片段。相反,它会在创建 Activity 时将其添加到 Java 代码中。这允许将其从布局中删除(使用remove()
or replace()
)
这可能无法解决您的问题,但这是片段造成的常见困难。您可以确保以正确的方式添加片段以允许它们被删除,然后如果这不能解决问题,我们可以进一步排除故障。