我正在学习如何使用片段.我有三个实例Fragment在类的顶部初始化.我将片段添加到这样的活动:
声明和初始化:
Fragment A = new AFragment();
Fragment B = new BFragment();
Fragment C = new CFragment();
Run Code Online (Sandbox Code Playgroud)
更换/添加:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, A);
ft.addToBackStack(null);
ft.commit();
Run Code Online (Sandbox Code Playgroud)
这些片段工作正常.每个片段都附加到活动,并保存到后台堆栈没有任何问题.
所以当我启动A时C,然后B,堆栈看起来像这样:
| |
|B|
|C|
|A|
___
Run Code Online (Sandbox Code Playgroud)
当我按下"后退"按钮时,会B被摧毁并C恢复.
但是,当我A第二次启动片段时,它不会从后端堆栈中恢复,而是添加到后端堆栈的顶部
| |
|A|
|C|
|A|
___
Run Code Online (Sandbox Code Playgroud)
但我想恢复A并销毁它上面的所有碎片(如果有的话).实际上,我只是喜欢默认的后台堆栈行为.
我该如何做到这一点?
预期:( A应该恢复,顶部碎片应该销毁)
| |
| |
| |
|A|
___
Run Code Online (Sandbox Code Playgroud)
编辑:(由A - C建议)
这是我尝试的代码:
private void selectItem(int position) { …Run Code Online (Sandbox Code Playgroud) 我的应用程序以AddressFragment开头.从NavigationDrawer我开始(以及其他)一个新的 AddressFragment:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new AddressFragment())
.addToBackStack(null)
.commit();
Run Code Online (Sandbox Code Playgroud)
但我宁愿回到第一个实例.我怎么能这样做?
或者更一般,我怎样才能找出片段的实例是否已经存在然后开始,如果是,否则创建一个?
当我的应用程序打开时,首先显示主屏幕。NavigationDrawer在主屏幕上,我在按下后打开了它。后来HamburgerIcon我转到不同的片段。当我在除 Home 之外的其他片段中时,Activity我需要显示后退按钮Toolbar才能回到上一个片段。但它每次都显示汉堡图标。如何做到这一点?
这是Toolbar在 XML 中设置的代码
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawerLayout"
tools:context="biz.fyra.myApp.ActivityTwo">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ccc"
android:minHeight="?attr/actionBarSize">
<ImageView
android:id="@+id/tooImage"
android:src="@drawable/latest"
android:layout_width="match_parent"
android:layout_gravity="center_horizontal"
android:layout_height="40dp" />
</android.support.v7.widget.Toolbar>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frame">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
android:id="@+id/navigationView"
app:menu="@menu/actionmenu"
android:background="@android:color/white">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Run Code Online (Sandbox Code Playgroud)
如何实现这一目标?
android android-fragments navigation-drawer android-toolbar hamburger-menu