如何在Android中动态更改开始目的地?

时间:2019-11-12 12:39:50

标签: android navigation

当前的导航结构如下:

Activity --> Fragment1 --> Fragment2

我想根据以下标志更改起始目标动态:

Activity --> Fragment1 --> Fragment2  
      |   
      -----> Fragment2

动态将起始目的地更改为Fragment2时,Fragment1不会回到Fragment2

导航类似于以下内容

<?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_frag">

    <fragment
        android:id="@+id/fragment1"
        android:name="bbin.mobile.ui.fragment1
        android:label="fragment1"
        tools:layout="@layout/layout_fragment1">
        <action
            android:id="@+id/action_fragment1_to_fragment2"
            app:enterAnim="@anim/anim_right_in"
            app:exitAnim="@anim/anim_left_out"
            app:popUpTo="@anim/anim_right_out"
            app:destination="@id/fragment2" />
    </fragment>

    <fragment
        android:id="@+id/fragment2"
        android:name="bbin.mobile.fragment2
        android:label="fragment2"
        tools:layout="@layout/layout_fragment2">
        <action
            android:id="@+id/action_fragment2_to_fragment1"
            app:popUpTo="@+id/fragment1"
            app:popUpToInclusive="true"
            app:destination="@id/fragment1" />
    </fragment>
</navigation>

活动布局如下:

<?xml version="1.0" encoding="utf-8"?>
<layout 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"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/frag"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="androidx.navigation.fragment.NavHostFragment"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/nav_frag"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

我尝试了以下链接

Is it possible to set startDestination conditionally using Android Navigation Architecture Component(Android Jetpack)?

但是当我将开始目的地更改为fragment1时,它将回到fragment2

如何在Android中动态更改开始目标,并且在将开始目标设置为fragment1时不会回到fragment2吗?

我错过了什么吗?预先感谢。

0 个答案:

没有答案