Home > Back-end >  navigate from main activity to fragment
navigate from main activity to fragment

Time:03-28

Im using navgraph to navigate between fragments.

Now, i implemet notifications in my app, so, when i click on the notification im goingo to the MainActivity with pending intent.

In the MainActivity I verify if the user is loged in, and manage the putExtra data to know to which fragment navigate. The problem is that the activity_main.xml doesn´t appear to add in the navgraph, so i don´t have MainActivityDirections.actionMainActivityToFragment(argument)

How can i navigate from the activity to one fragment with arguments?

CodePudding user response:

There is a solution for such a case:

val navController = findNavController(R.id.nav_host_test)
navController.navigate(R.id.action_global_test)

Firstly you need to need to access your navController where the id is taken from the view's id in your Activity.

enter image description here

then you need to create a global action, like this (pay attention only to the action):

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

    <action
        android:id="@ id/action_global_test"
        app:destination="@id/second_fragment"
        app:launchSingleTop="false"
        app:popUpTo="@ id/mobile_navigation"
        app:popUpToInclusive="true" />

    <fragment
        android:id="@ id/first_fragment"
        android:name="com.grappim.myapplication.ui.home.HomeFragment"
        android:label="@string/title_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@ id/second_fragment"
        android:name="com.grappim.myapplication.ui.dashboard.DashboardFragment"
        android:label="@string/title_dashboard"
        tools:layout="@layout/fragment_dashboard" />

</navigation>

CodePudding user response:

I implemented something like @Grigoriym but with arguments as needed

MainActivity

val bundle = Bundle()
bundle.putParcelable("OrderNotification",navigator.order)
navController.navigate(R.id.orderDetailsFragment, bundle)

and in the orderDetialsFragment

private val args: OrderDetailsFragmentArgs by navArgs()


val arg = arguments?.getParcelable<OrderUI>("OrderNotification")
    if(arg != null){
        orderArg = arg
    }else{
        orderArg = args.order
    }
  • Related