Navigation Architecture Component、使ったらいろいろ楽になった
— 心理的安全性がほしい (@shuma_yoshioka) May 13, 2018
いままでのAndroid開発では、たとえばディープリンクにはGradleからAndroidManifestを書き換える黒魔術を、たとえばルーティングやナビゲーションにはオレオレフレームワークもどきを作って使ってきましたが、Google I/O 2018で発表された Navigation Architecture Component を使うと大変便利でした。
とりあえず使ってみたメモです。
NavHostFragment
というのを持ち、そのさらに入れ子でアプリケーションドメインのFragmentが管理・表示されるNavHostFragment
が内包するNavController
というやつがルーティングをしている
R.id.*
で指示するNavController
がよしなにルーティングする
intent-filter
を書き換える各コンポーネントが複雑に絡み合っているので、ゼロから作っていく時は順序にコツがある気がしました。
私の所感としては、
res/navigation/*.xml
の定義がスムーズです。
使ってみる。とりあえず「入力された文字をそのまま表示するアプリ」を目指します。
プロジェクトルートのbuild.gradle
へ以下のように書きます。
buildscript { ... ext.navigation_architecture_component_version = '1.0.0-alpha01' ...
同ファイルのdependenciesへ以下を追加します。
buildscript { ... dependencies { ... classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:${navigation_architecture_component_version}" ...
アプリケーションモジュールのbuild.gradle
冒頭に以下プラグインを追加します。
... apply plugin: 'androidx.navigation.safeargs' ...
同じファイルに依存するライブラリを追加します。
dependencies { ... implementation "android.arch.navigation:navigation-fragment:${navigation_architecture_component_version}" implementation "android.arch.navigation:navigation-ui:${navigation_architecture_component_version}" ...
本質から外れるけれどRelativeLayout
はdon't useでuse ConstraintLayout
らしいので、このサンプルアプリではConstraintLayout
の依存も加えます。
... implementation 'com.android.support.constraint:constraint-layout:1.1.0' ...
このサンプルアプリでは以下の画面を作ろうかな、
これらは一般的なAndroidアプリケーション開発となんら違いが無いので、詳細な解説は飛ばします。
また、画面遷移に関わるボタンクリック時のインタラクション等はこの時点では実装しません。要は、
package jp.s64.android.prototype.myechoapplication import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup class *Fragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.*_fragment, container, false) } }
程度の記述のみです。
TitleFragment | InputFragment |
---|---|
![]() |
![]() |
ResultFragment | AboutFragment |
---|---|
![]() |
![]() |
Google I/Oのサンプルを見る限り、命名規則が従来のfragment_*.xml
やlayout_*.xml
ではなく*_fragment.xml
となっている方がこれからはイケてるみたい。
res/navigation/*.xml
の定義キモです。res
ディレクトリでnavigation
というディレクトリを作成し、その中に任意の名前のxmlを記述します。私の場合、app_navigation.xml
としました。
ナビゲーションの対象とするFragmentをひととおり記述します。
<navigation ... > ... <fragment android:id="@+id/launcher_title" android:name="jp.s64.android.prototype.myechoapplication.TitleFragment" android:label="@string/title" tools:layout="@layout/title_fragment" /> <fragment android:id="@+id/flow_input" android:name="jp.s64.android.prototype.myechoapplication.InputFragment" android:label="@string/input" tools:layout="@layout/input_fragment" /> <fragment android:id="@+id/flow_result" android:name="jp.s64.android.prototype.myechoapplication.ResultFragment" android:label="@string/result" tools:layout="@layout/result_fragment" /> <fragment android:id="@+id/screen_about" android:name="jp.s64.android.prototype.myechoapplication.AboutFragment" android:label="@string/about" tools:layout="@layout/about_fragment" /> ...
各要素のandroid:id
は遷移先として指定されるものなので、たとえば起動時の画面ならlauncher_*
などとするのが良いです。
Aboutが操作フローから独立した画面なので暫定的にscreen_*
としましたが、はたして命名のベストプラクティスはなんでしょうか...
android:label
には文字列またはstringリソースが使えます。これはToolbarに表示されるtitleです。
次にルート要素に起動時の初期画面を指定します。
<navigation .... app:startDestination="@id/launcher_title"> ...
TitleからInputへ遷移できるようにします。@+id/launcher_title
のfragment
要素内にaction
を追加します。
<fragment android:id="@+id/launcher_title" ... > <action android:id="@+id/action_launcher_title_to_flow_input" app:destination="@id/flow_input" /> </fragment>
同様に、InputFragment
からResultFragment
へ遷移できるようにaction
を記述します。
<fragment android:id="@+id/flow_input" ... > <action android:id="@+id/action_flow_input_to_flow_result" app:destination="@id/flow_result" /> </fragment>
ResultFragment
が入力された文字を受け取れるように、argumentを定義します。
<fragment android:id="@+id/flow_result" ... > <argument android:name="input_text" android:defaultValue="No Input!" app:type="string" /> </fragment>
MainActivity
とでもして作成します。レイアウトは例えば以下のようになります。
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivityActivity"> <android.support.design.widget.BottomNavigationView android:id="@+id/bottomNavigation" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:menu="@menu/menu_bottom_navigation" /> <fragment android:id="@+id/navHost" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="0dp" app:defaultNavHost="true" app:layout_constraintBottom_toTopOf="@+id/bottomNavigation" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:navGraph="@navigation/app_navigation" /> </android.support.constraint.ConstraintLayout>
ポイントはNavHostFragment
が画面全体を覆っていることと、app:navGraph
でさきほどのxmlを指定していること。
BottomNavigationView
または (DrawerLayout
で包んだ) NavigationView
を使うと、app:menu
で指定したメニューからよしなに遷移をしてくれます。
今回つくったres/menu/menu_bottom_navigation.xml
の内容です。
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@id/launcher_title" android:icon="@drawable/ic_home" android:title="@string/title"/> <item android:id="@id/screen_about" android:icon="@drawable/ic_info" android:title="@string/about"/> </menu>
こちらのポイントはandroid:id
に指定している内容がapp_navigation.xml
の各fragment
のものであること。ここに指定したものを呼び出してくれます。
Activityのコードを書いていきます。以下のようになりました。
package jp.s64.android.prototype.myechoapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.design.widget.BottomNavigationView import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.NavigationUI class MainActivity : AppCompatActivity() { lateinit var navHost: NavHostFragment override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) navHost = supportFragmentManager .findFragmentById(R.id.navHost) as NavHostFragment val bottomNavigation = findViewById<BottomNavigationView>(R.id.bottomNavigation) NavigationUI.setupActionBarWithNavController(this, navHost.navController) NavigationUI.setupWithNavController(bottomNavigation, navHost.navController) } /* override fun onOptionsItemSelected(item: MenuItem): Boolean { return NavigationUI.onNavDestinationSelected(item, navHost.navController) || super.onOptionsItemSelected(item) } */ override fun onSupportNavigateUp(): Boolean { return navHost.navController.navigateUp() || super.onSupportNavigateUp() //return NavigationUI.navigateUp(drawer, navHost.navController) || super.onSupportNavigateUp() } }
NavigationUI.setupActionBarWithNavController
でタイトルなどActionBar
を、NavigationUI.setupWithNavController
でBottomNavigationView
のクリックイベント等をNavHostFragment
の内包するNavController
と繋ぎ込みます。
onOptionsItemSelected
はActionBar
のmenuから直接遷移させる時用の記述です。必要に応じてコメントアウトしてください。
onSupportNavigateUp
はActionBar
でupした際に画面スタックをpopさせるために必要です。また、Drawerを利用する場合はコメントアウトしてあるような記述を用いることで可能です。
各画面のボタンクリック等を繋ぎます。
TitleFragment
は単に以下のような記述を追加すれば十分です。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.findViewById<Button>(R.id.button).setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_launcher_title_to_flow_input)) }
createNavigateOnClickListener
には遷移先fragmentのidではなく、actionのidを指定しているのがポイントです。
対しInputFragment
では次の画面へ値を渡す必要があります。今回の場合は以下のように記述できます。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val editText = view.findViewById<EditText>(R.id.editText) view.findViewById<Button>(R.id.button2).setOnClickListener { Navigation.findNavController(it).navigate( R.id.action_flow_input_to_flow_result, ResultFragmentArgs.Builder() .setInput_text(editText.text.toString()) .build() .toBundle() ) } }
ResultFragmentArgs
はnavigation-safe-args-gradle-plugin
が自動生成しているもので、navigationのxmlに記述した内容が元になっています。
同様に、ResultFragment
でも渡された値を表示できるようにします。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val args = ResultFragmentArgs.fromBundle(arguments) view.findViewById<TextView>(R.id.textView).text = args.input_text }
以上で基本的な機能の実装は完了です。
らくちん!
app_navigation.xml
内のfragment
要素に、以下のように記述します。今回はaboutに対応するリンクにしました。
<fragment android:id="@+id/screen_about" ... > <deepLink app:uri="http://example.com/about"/> </fragment>
AndroidManifest.xml
のActivity内に、以下のように記述します。
... <activity android:name=".MainActivity"> ... <nav-graph android:value="@navigation/app_navigation"/> ... </activity> ...
以上で完了です。
らくちん!
よさそう
※ 今回のコードはこちらに置きました