我正在开发一个带有一些片段的Android应用程序。
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
tools:context=".MainActivity">
<include layout="@layout/content_main" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
内容_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<fragment
android:id="@+id/nav_host_fragment_content_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
我也有一个 nav_graph.xml,但是当我发布它时,这个问题被归类为垃圾邮件:)
我这样导航
Navigation.findNavController(this, R.id.nav_host_fragment_content_main)
.navigate(R.id.action_global_showIngredientListFragment);
或者这个:
ShowDrinkListFragmentDirections.ActionDrinkListToEditDrink action =
ShowDrinkListFragmentDirections.actionDrinkListToEditDrink();
action.setDrinkDBId(0);
Navigation.findNavController(v).navigate(action);
我在onCreateView(...)中初始化整个Fragment
我现在遇到的问题是,如果我通过设备的后退按钮到达主要包含 ListView 的 Fragment,则不会显示通过向设置的适配器插入和删除视图来对 ListView 内容进行的更改。如果我按照上面所示的方式导航到它,一切都会按照我想要的方式处理。我确实在片段上记录了一些生命周期方法,这些方法在通过所描述的两种方式到达片段时被调用。它们是相同的并且看起来很合理。离开片段时:onPause、onStop、onDestroyview。导航返回时(与单击导航或后退按钮相同):onCreateView onViewCreated、onStart、onResume。 我无法解释为什么我在按上面所示的方式导航时看到 UI 中发生的更改,而不是通过单击后退按钮,即使在 customMade 适配器上的操作发生时调用了相同的方法。
可以通过将 ListView 的操作移至
onViewStateRestored(...)
。仍然不知道为什么只有通过后退按钮进入视图才需要这样做。