[英]Reload Fragment after popBackStack
您要實現的實際上是在訪問 backStack 時的跳過操作。
有兩種方法可以解決這個問題
transaction.add(R.id.main_activity_container, FirstFragment, "FirstFragment");
transaction.replace(R.id.main_activity_container, Second, "SECOND");
transaction.replace(R.id.main_activity_container, Third, "THIRD");
然后覆蓋 onBackPressed 以檢查用戶是否在按下后退按鈕的第三個片段中應該 go 到第一個片段。
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getFragments().get(lastStack).getTag().equalsIgnoreCase("THIRD")){
//fragment transaction to go to the first screen
}
}
.addToBackStack(null)
一樣,然后從第三個片段正常彈出你可以使用導航組件庫來解決這個問題!
這將是您的 nav_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_graph"
app:startDestination="@id/AFragment">
<fragment
android:id="@+id/AFragment"
android:name="ir.inbo.navigationComponenetBug.AFragment"
android:label="AFragment"
tools:layout="@layout/fragment_a">
<argument
android:name="someLong"
app:argType="long" />
<action
android:id="@+id/action_AFragment_to_BFragment"
app:destination="@id/BFragment" />
</fragment>
<fragment
android:id="@+id/BFragment"
android:name="ir.inbo.navigationComponenetBug.BFragment"
android:label="BFragment"
tools:layout="@layout/fragment_b">
<argument
android:name="someLong"
app:argType="long" />
<action
android:id="@+id/action_BFragment_to_CFragment"
app:destination="@id/CFragment" />
</fragment>
<fragment
android:id="@+id/CFragment"
android:name="ir.inbo.navigationComponenetBug.CFragment"
android:label="CFragment"
tools:layout="@layout/fragment_c" >
<argument
android:name="someLong"
app:argType="long" />
<action
android:id="@+id/action_CFragment_to_AFragment"
app:destination="@id/AFragment"
app:popUpTo="@id/AFragment"
app:popUpToInclusive="true" />
</fragment>
</navigation>
在 AFragment 中,您必須將邏輯移動到 onViewCreated 或 onCreateView,因為當您從 AFragment 導航到 Bfragment 時,片段生命周期,Afragment 的視圖將被破壞,當您從 Cfragment 回到 Afragment 時,將調用 onViewCreated 和 onViewCreate
這是您確切用例的谷歌示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.