Issue
I have a single activity which has a bottom navigation view in order to open different fragments. The top level/default fragments loads data from firebase and then i want to pass that data to different fragments when user switches to different fragment.
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>
My MainActivity's OnCreate has:
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
NavController navController = Navigation.findNavController(this, R.id.fragment);
NavigationUI.setupWithNavController(bottomNavigationView, navController);
When HomeFragment loads the data from firestore. I want to pass 2 values to the other fragments. I did look up the docs but I couldn't understand.
Solution
The easiest solution for this is to just use Viewmodel instead of passing it between activity and the fragment. Then u pass the activity on the ViewModel so every fragment and the parent have the same ViewModel.
This is an example of how to do it val viewModel by activityViewModels<The ViewModel that u made>()
Answered By - Tensky
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.