11
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Navigation Componentの注意点

Last updated at Posted at 2020-03-26

Navigation Componentを使っていて嵌ったポイント

update
@FKbelm さんからfindFragmentByIdを使えば大丈夫だと教えてもらいました。

ハマったこと

Navigation Componentを使って、ToolbarをActivityに持たせていたら、該当のViewを表示する時に

java.lang.IllegalStateException: Activity Caused by: java.lang.IllegalStateException: Activity {Activity} does not have a NavController set on  {nav_host_fragmentのid}

が出た。

原因

FragmentContainerViewを使って、

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="enterAlways|scroll" />

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:navGraph="@navigation/nav_graph" />

のように書いてると

toolbar.setupWithNavController(findNavController(R.id.nav_host_fragment))

でNavControllerが見つからないと例外が投げられる。

対策

FragmentContainerViewじゃなくfragmentを使えばいい。

val navController = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) 
toolbar.setupWithNavController(navController!!.findNavController())

という呼び方をすれば大丈夫そう

余談

lintでfragmentをFragmentContainerViewに変えろって言われるけど、今は無視するしかなさそう。

11
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?