Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Nav Controller in AndroidX?

I'm using the following activity layout with a fragment and a BottomNavigationView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:id="@+id/fragment"
        android:layout_weight="1"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:newGraph="@navigation/navigation_bottom"
        app:defaultNavHost="true"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bottom_navigation_view"
        app:menu="@menu/bottom_navigation_menu"/>
</LinearLayout>

In my activity, I'm trying to setup the Nav Controller this but I'm getting the following error:

Cannot resolve method 'setupWithNavController(androidx.navigation.NavController)'

This is what I have tried:

navController = Navigation.findNavController(this, R.id.fragment);
BottomNavigationView bnv = findViewById(R.id.bottom_navigation_view);
bnv.setupWithNavController(navController); //Error
NavigationUI.setupActionBarWithNavController(this, navController);

My dependencies:

implementation 'android.arch.navigation:navigation-fragment:1.0.0-rc02'
implementation 'android.arch.navigation:navigation-ui:1.0.0-rc02'

How can I wire this up? Thanks!

like image 212
Johans Bormman Avatar asked Dec 14 '22 12:12

Johans Bormman


2 Answers

The syntax bnv.setupWithNavController uses a Kotlin extension method - you have to use Kotlin and the -ktx dependencies to have access to Kotlin extensions as per the note in the Declaring dependencies documentation:

implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-rc02'
implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-rc02'

If you're writing Java code, you need to use the NavigationUI methods directly:

NavigationUI.setupWithNavController(bnv, navController);
like image 57
ianhanniballake Avatar answered Dec 28 '22 06:12

ianhanniballake


Check these two properties are enable in your gradle.properties

android.useAndroidX=true

android.enableJetifier=true

Update

And verify you are using these libs too.

implementation 'androidx.core:core: 1.0.1'
implementation 'androidx.appcompat:appcompat:1.0.2
like image 32
Hussnain Haidar Avatar answered Dec 28 '22 06:12

Hussnain Haidar