Conditional navigation with Navigation Component & View Model | Sharing Data using View Model

Published: 19 May 2021
on channel: Kotlin Tpoint
1,080
29

Conditional navigation with navigation component and View Model
Sharing Data between fragments using View Model

def nav_version = "2.3.5"
// Java language implementation
implementation "androidx.navigation:navigation-fragment:$nav_version"
implementation "androidx.navigation:navigation-ui:$nav_version"

def lifecycle_version = "2.3.1"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"

1) navigation component with ProfileFragment, LoginFragment and HomeFragment,

2) Connect navigation component with Activity

< androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />

3) create action from HomeFragment to ProfileFragment and ProfileFragment to LoginFragment

Navigation.findNavController(view).navigate(R.id.action);

4) Create ViewModel class with field String (Username)

5) inside ProfileFragment make sure User has visited LoginFragment and Username set with ViewModel

UserViewModel viewModel = ViewModelProviders.of(owner).get(UserViewModel.class);
viewModel.getUserName().observe(...);

6) Get Value of Username from ViewModel inside ProfileFragment

7) inside LoginFragment when Username in ViewModel and also popBackStack() to navigate on ProfileFragmentBack

NavHostFragment.findNavController(this).popBackStack();

8) Run and test the output

#navigation #android #coding #component #viewmodel #datasharing


On this page of the site you can watch the video online Conditional navigation with Navigation Component & View Model | Sharing Data using View Model with a duration of hours minute second in good quality, which was uploaded by the user Kotlin Tpoint 19 May 2021, share the link with friends and acquaintances, this video has already been watched 1,080 times on youtube and it was liked by 29 viewers. Enjoy your viewing!