使用导航组件参数将数据传递到多个片段

时间:2020-09-17 08:40:21

标签: android android-fragments android-navigation

我有一个活动,该活动具有底部导航视图,以便打开不同的片段。 顶层/默认片段从Firebase加载数据,然后当用户切换到不同片段时,我想将该数据传递给不同片段。

Navigation.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/navigation"
    app:startDestination="@id/homeFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.ankitrath.finderr.HomeFragment"
        android:label="fragment_home"
        tools:layout="@layout/fragment_home" />
    <fragment
        android:id="@+id/searchFragment"
        android:name="com.ankitrath.finderr.SearchFragment"
        android:label="fragment_search"
        tools:layout="@layout/fragment_search" />
    <fragment
        android:id="@+id/requestFragment"
        android:name="com.ankitrath.finderr.RequestFragment"
        android:label="fragment_request"
        tools:layout="@layout/fragment_request" />
    <fragment
        android:id="@+id/friendFragment"
        android:name="com.ankitrath.finderr.FriendFragment"
        android:label="fragment_friend"
        tools:layout="@layout/fragment_friendd" />
</navigation>

我的MainActivity的OnCreate具有:

BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
        NavController navController = Navigation.findNavController(this,  R.id.fragment);
        NavigationUI.setupWithNavController(bottomNavigationView, navController);

HomeFragment从Firestore加载数据时。我想将2个值传递给其他片段。 我确实查找了文档,但听不懂。

1 个答案:

答案 0 :(得分:2)

最简单的解决方案是只使用Viewmodel,而不是在活动和片段之间传递它。然后,您在ViewModel上传递活动,因此每个片段和父对象都具有相同的ViewModel。 这是一个val viewModel by activityViewModels<The ViewModel that u made>()

的示例。