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

Passing data to Multiple Fragments using Navigation Component Arguments

我有一个 activity,它有一个底部导航视图,以便打开不同的片段。 顶部 level/default 片段从 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 个值传递给其他片段。 我确实查阅了文档,但我无法理解。

最简单的解决方案是只使用 Viewmodel 而不是在 activity 和片段之间传递它。然后你在 ViewModel 上传递 activity 这样每个片段和父级都有相同的 ViewModel。 这是如何操作的示例 val viewModel by activityViewModels<The ViewModel that u made>()

您可以使用 VIEWHOLDER 在片段或活动之间共享数据,这是一个示例

在您的应用中 gradle 添加此实现

def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"

像这样创建一个 viewHolder Class

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class SharedDataViewModel: ViewModel() {
    private val _selectedCycle = MutableLiveData<Cycle>()
    val selectedCycle: LiveData<Cycle> = _selectedCycle

    private val _isAdmin = MutableLiveData<Boolean>()
    val isAdmin: LiveData<Boolean> = _isAdmin

    fun getSelectedCycle():Cycle {
        return _selectedCycle.value!!
    }
    fun setSelectedCycle(cycle: Cycle) {
        _selectedCycle.value = cycle
    }

    fun getIsAdmin():Boolean {
        return _isAdmin.value!!
    }
    fun setIsAdmin(value: Boolean) {
        _isAdmin.value = value
    }
}

并像在每个片段中那样使用它或 activity

 private val sharedData: SharedDataViewModel by activityViewModels()

然后设置或获取新值

sharedData.getIsAdmin()
sharedData.setIsAdmin(true)