如何在片段目标位置添加NavHostFragment?

时间:2019-09-17 08:30:02

标签: android-jetpack android-jetpack-navigation android-navigation-bar android-navigation-graph

我的目标是通过复杂的导航体系结构以最佳方式理解和使用导航组件(我想)。

要创建全局上下文,我使用一个主要的BottomNavigationBar包含5个项目。对于关联片段的管理,我使用Google给出的示例:https://github.com/googlesamples/android-architecture-components/tree/master/NavigationAdvancedSample

但是我的情况比底数还要复杂。在底部栏启动的片段之一的目的地中,我有另一个RecyclerView菜单和一个片段容器,可在片段之间导航。我在这里放置了主图表的重要部分:

<?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/main"
    app:startDestination="@id/mainFragment">
    <fragment
        android:id="@+id/mainFragment"
        android:name="com.exemple.fragment.MainFragment"
        android:label="@string/main_label"
        tools:layout="@layout/mainFragment">
        <action
            android:id="@+id/action_mainFragment_to_goScreen"
            app:destination="@id/goScreen">
        </action>
    </fragment>
    <fragment
        android:id="@+id/goScreen"
        android:name="com.exemple.fragment.GoFragment"
        android:label="@string/goLabel"
        tools:layout="@layout/fragment_go">
        <action
            android:id="@+id/action_goScreen_to_mainFragment"
            app:destination="@id/mainFragment" />
        <argument
            android:name="arg1"
            app:argType="com.exemple.customType"
            android:defaultValue="@null"
            app:nullable="true" />
        <argument
            android:name="arg2"
            app:argType="string"
            android:defaultValue="@null"
            app:nullable="true" />
    </fragment>
</navigation>

以及带有底部栏的xml来启动该图:

<?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="com.exemple.MainActivity">

    <RelativeLayout
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/fake_toolbar"
            android:layout_width="0dp"
            android:layout_height="0dp"/>

        <androidx.fragment.app.FragmentTabHost
            android:id="@+id/main_host_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/bottom_navigation" />

        <!-- navigation bottom -->
        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:layout_alignParentBottom="true"
            android:background="@color/navigationBarColor"
            app:itemIconTint="@color/textColorNavigationBar"
            app:itemTextColor="@color/textColorNavigationBar"
            app:menu="@menu/menu_bottom_navigation" />
    </RelativeLayout>
</layout>

下面是与go片段(目标)相对应的图形示例:

<?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/go"
    app:startDestination="@id/firstGoFragment">

    <action android:id="@+id/action_to_firstGoFragment"
        app:destination="@id/firstGoFragment"/>
    <fragment
        android:id="@+id/firstGoFragment"
        android:name="com.exemple.go.firstGoFragment"
        android:label="@string/firstGoFragmentLabel"
        tools:layout="@layout/firstGoFragment" >
    </fragment>

    <action android:id="@+id/action_to_secondFragment"
    app:destination="@id/secondFragment"/>
    <fragment
        android:id="@+id/secondFragment"
        android:name="com.exemple.go.SecondFragment"
        android:label="@string/secondFragmentLabel"
        tools:layout="@layout/secondFragment" >
    </fragment>
</navigation>

关联xml是:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorGreyLight"
        android:clickable="true"
        android:focusable="true">

        <RelativeLayout
            android:id="@+id/linearLayout3"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <androidx.appcompat.widget.AppCompatImageView
                android:id="@+id/quit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginStart="16dp"
                android:paddingBottom="15dp"
                android:paddingEnd="15dp"
                android:paddingTop="15dp"
                app:srcCompat="@drawable/ic_quit_white" />

            <com.teedji.mobeelity.custom.CustomTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="@string/go"
                android:textColor="@color/colorWhite"
                android:textSize="17sp"
                android:textStyle="bold" />

        </RelativeLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/goMenu"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/colorWhite"
            android:overScrollMode="never"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/linearLayout3" />

        <!-- include fragment child container -->
        <fragment
            android:id="@+id/go_nav_host_fragment_container"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_marginTop="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/goMenu"
            app:navGraph="@navigation/go"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

现在,我只需使用

即可转到“转到”屏幕
findNavController().navigate(MainFragmentDirections.actionMainFragmentToGoScreen(arg1, arg2))

findNavController().navigate(R.id. action_mainFragment_to_goScreen)

但是当我使用Go片段时,使用findNavController()找到的navController仍然是mainFragment之一。因此navigate()功能未找到操作ID。为了解决这个问题,我不得不像这样在GoFragment中更改navHost的编程方式:

override fun onCreate(savedInstanceState: Bundle?) {
        Log.i(LOG_TAG, "onCreate")
        super.onCreate(savedInstanceState)
        if( fragmentManager != null ) {
            // If the Nav Host fragment exists, return it
            val existingFragment = fragmentManager!!.findFragmentByTag(FRAGMENT_TAG) as NavHostFragment?
            existingFragment?.let { navHostGoFragment = it }

            // Otherwise, create it and return it.
            if ( navHostGoFragment == null) {
                navHostGoFragment = NavHostFragment.create(R.navigation.go)
                fragmentManager!!.beginTransaction()
                        .add(R.id.go_nav_host_fragment_container, navHostGoFragment!!, FRAGMENT_TAG)
                        .commit()
            }
        }else {
            Log.e(LOG_TAG, "fragmentManager is null so I can't find the fragment host")
        }
}

,然后使用navHostGoFragment!!.navController.navigate(R.id.action_to_firstGoFragment)在新容器中导航 但是这样做的话,我的firstFragment被创建了两次(我可以在日志中看到它),并且会产生诸如Cannot add the same observer with different lifecycles之类的问题(我可以通过添加

来解决此问题
if  (model.getLiveData().hasObservers()) {
        model.getLiveData().removeObserver(observer)
    }

之前

model.getLiveData().observe(viewLifecycleOwner, observer)

) 但是我认为我没有像应该做的那样导航部分...

您能否提供任何帮助以稳定地更有效地完成这项工作?

1 个答案:

答案 0 :(得分:0)

如果您使用的是Kotlin Android扩展程序或go_nav_host_fragment_container.findNavController().navigate(),请尝试使用findViewById(R.id.go_nav_host_fragment_container).findNavController().navigate(),并查看其是否有效。