Navigation controller navigate from startDestination fragment getting exception

Viewed 8449
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

2 Answers

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));

R.id.homePageFragment is not a NavHostFragment do it like thie

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

and call in code like this

                Navigation.findNavController(requireActivity(), R.id.fragment_container_view).navigate(R.id.show_one)

Related