Navigation controller navigate from startDestination fragment getting exception

Libin Thomas picture Libin Thomas · Sep 21, 2018 · Viewed 7.6k times · Source
java.lang.IllegalArgumentException: ID does not reference a View inside this Activity

    mBtHome.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {



                    Navigation.findNavController(getActivity(), R.id.homePageFragment);
                }
            });  

mBtHome button inside startDestination fragment

navigation graph xml file.

<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/nav_file"
    app:startDestination="@id/mainFragment">
    <fragment
        android:id="@+id/mainFragment"
        android:name="com.example.libin.navigationhelphertest.ui.main.MainFragment"
        android:label="main_fragment"
        tools:layout="@layout/main_fragment">
        <action
            android:id="@+id/action_mainFragment_to_homePageFragment"
            app:destination="@id/homePageFragment" />
        <action
            android:id="@+id/action_mainFragment_to_usersListFragment"
            app:destination="@id/usersListFragment" />
    </fragment>
    <fragment
        android:id="@+id/homePageFragment"
        android:name="com.example.libin.navigationhelphertest.ui.main.HomePageFragment"
        android:label="fragment_home_page"
        tools:layout="@layout/fragment_home_page" />
    <fragment
        android:id="@+id/usersListFragment"
        android:name="com.example.libin.navigationhelphertest.ui.main.UsersListFragment"
        android:label="fragment_users_list"
        tools:layout="@layout/fragment_users_list" />
</navigation>

navigation/nav_file added inside MainActivity xml file NavHostFragment alsoe included ,Also defaultNavHost= "true" added

Answer

Android Team picture Android Team · Sep 21, 2018

As per the above code to navigate from one fragment to another on click of the button, there are many ways.

Navigation class gives you the createNavigateOnClickListner() method you just need to pass the fragment action id.

Try the below code

 mBtHome.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_mainFragment_to_homePageFragment));