Tuesday, 2 July 2019

Using Navigation Component inside BaseFragment

In my application I have an OptionsMenu which is used by many Fragments. Therefore I created the following BaseFragment:

abstract class BaseFragment : Fragment() {

private lateinit var navController: NavController

protected fun askForPermissions(permissionRequestCode: Int, vararg permissions: String) {
    requestPermissions(permissions, permissionRequestCode)
}

protected fun checkPermission(permission: String, activity: Activity): Boolean = when {
    Build.VERSION.SDK_INT < Build.VERSION_CODES.M -> true // It is not needed at all as there were no runtime permissions yet
    else -> ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED
}

override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
    inflater!!.inflate(R.menu.menu_topbar, menu)

    @SuppressLint("RestrictedApi")
    if (menu is MenuBuilder) {
        menu.setOptionalIconsVisible(true)
    }

    super.onCreateOptionsMenu(menu, inflater)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    navController = Navigation.findNavController(view!!)

    return when (item.itemId) {
        R.id.menu_topbar_profile -> {
            navController.navigate(actionBaseToProfile())
            true
        }
        R.id.menu_topbar_favorites -> {
            navController.navigate(actionBaseToFavorites())
            true
        }
        R.id.menu_topbar_help -> {
            navController.navigate(actionBaseToHelp())
            true
        }
        else -> false
    }
}

}

And in the navigation file I added the BaseFragment and the target Fragments. Here is a snippet:

    <fragment
    android:id="@+id/fragment_base"
    android:name="com.test.scanner.base.BaseFragment">

    <action
        android:id="@+id/action_base_to_profile"
        app:destination="@id/fragment_profile" />
</fragment>

<fragment
    android:id="@+id/fragment_profile"
    android:name="com.test.scanner.ui.profile.ProfileFragment"
    tools:layout="@layout/fragment_profile" />

As you can see I don't defined a layout for the BaseFragment because there is no one. I always get an IllegalArgumentException if I want to navigate to a specific screen (e.g. ProfileFragment) by clicking on an element of the OptionsMenu. Here is the exception:

java.lang.IllegalArgumentException: navigation destination com.test.scanner.debug:id/action_base_to_profile is unknown to this NavController

How we can use the Navigation Component inside a BaseFragment. Is it possible at all or is there another solution for this case?



from Using Navigation Component inside BaseFragment

No comments:

Post a Comment