【发布时间】:2016-11-03 04:29:19
【问题描述】:
我尝试实现一种可以将不同片段加载到一个容器视图元素中的活动。我关注Building a Flexible UI Training。问题:替换片段时,我仍然可以在后台看到被替换的片段。
我看到我的问题已经被问过很多次了。但是,我找到的所有答案似乎都只是一种解决方法(设置片段的背景颜色)或不适用。
这是我到目前为止的设置:
活动的 XML 布局包含一个 FrameLayout 作为片段的容器:
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
id fragment_container 在项目的其他地方没有使用。
第一个片段的完整 XML 布局:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="First Fragment" />
第二个片段的完整XML布局:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ff0000"
android:text="Fragment Second" />
第一个片段的类文件如下所示(第二个片段的类类似):
public class FirstFragment extends Fragment {
public FirstFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
在活动的 onCreate 方法中,我加载了第一个片段:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// load first fragment
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, new FirstFragment())
.commit();
}
}
选择菜单项时,我尝试将第一个片段用第二个片段替换为活动的 onOptionsItemSelected方法:
getFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new SecondFragment())
.addToBackStack(null) // <-- does not make any difference if left out
.commit();
结果是文本“Fragment Second”以红色打印在文本“First Fragment”上方。
解决此问题的“正确方法”(即不只是设置背景颜色)是什么?
【问题讨论】: