android fragment_Android 开发:Navigation 返回上一个Fragment避免重建View的方法
时间: 2023-06-26 18:09:20 浏览: 78
在 Navigation 中返回上一个 Fragment 默认是会重新创建 View 的,但是可以通过设置 Fragment 的属性来避免这种情况。
在当前 Fragment 中,可以通过调用 `setRetainInstance(true)` 方法来保存 Fragment 实例,这样在返回时就不会重新创建实例。同时,需要注意的是,当使用这种方法时,Fragment 中的成员变量和状态也会被保存,因此需要注意状态的恢复。
另外一种方法是在 Navigation 的 Action 中设置 `popUpTo` 和 `popUpToInclusive` 属性,这样返回时会将指定的 Fragment 弹出栈,而不是重新创建。
例如:
```xml
<action
android:id="@+id/action_detail_to_list"
app:destination="@id/listFragment"
app:popUpTo="@id/detailFragment"
app:popUpToInclusive="true" />
```
这样,在从 DetailFragment 返回 ListFragment 时,DetailFragment 就会被弹出栈,而不是重新创建。
需要注意的是,这种方法只适用于返回到指定的 Fragment,如果需要返回上一个 Fragment,还是需要使用第一种方法。
相关问题
<LinearLayout 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:orientation="vertical" android:background="#6A2BCE74" tools:context=".MainActivity"> <androidx.fragment.app.FragmentContainerView android:id="@+id/fcv" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bnv" android:layout_width="match_parent" android:layout_height="wrap_content" app:itemTextColor="@drawable/selector_bottom" /> </LinearLayout>什么意思
这是一个 Android 的布局文件,使用 LinearLayout 作为根布局,设置了垂直方向排列子视图,并设置了背景颜色。其中包含两个子视图:
1. FragmentContainerView:用于展示 Fragment 的容器,设置了宽度为 match_parent,高度为 0dp,并设置了权重为 1,使其占据剩余的空间。
2. BottomNavigationView:用于底部导航栏,设置了宽度为 match_parent,高度为 wrap_content。同时使用了一个名为 selector_bottom 的 Drawable 作为 item 的文本颜色。
fragment和BottomNavigationView全面屏布局怎么设置
对于全面屏布局,可以使用以下代码:
```
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
```
对于fragment和BottomNavigationView的布局,可以使用以下代码:
```
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:menu="@menu/bottom_navigation_menu" />
```
其中,nav_graph和bottom_navigation_menu需要根据实际情况进行修改。