Androidアプリ開発勉強(2) - Navigationの基本
Navigationを用いて画面遷移をやってみる。具体的には以下の処理を行う。 Fragment01とFragment02を用意する Fragment01でボタンが押されたらFragment02に遷移する Android Kotlin Fundamentals Courseでの03辺りを勉強した記録なので、詳しいことはそちらに載っている。 Navigationについて 異なるFragment間の遷移を制御する仕組み。遷移の設定を視覚的に行えるらしい。 これ以前はIntentという仕組みを用いていたらしい。これについては必要になりそうならいつか調べる。 プロジェクト作成 Empty Activityを選択し、名前をNavigation Testとする。 build.gradle(Module: app)でDataBindingを有効にしておく。 Fragmentの作成 layouts/にFragmentを作成する。“Create layout XML?“だけチェックをつけておく。Fragmentは2つ作成し、それぞれ"Fragment01"と"Fragment02"とする。xmlファイルはそれぞれfragment_fragment01.xml、fragment_fragment02.xmlとする。 まずTextViewのtext要素に設定するための定数をstrings.xmlに内容を追加しておく。 1 2 3 4 5 6 7 8 9 <resources> <string name="app_name">NavigationTest</string> <!-- TODO: Remove or change this placeholder text --> <string name="hello_blank_fragment">Hello blank fragment</string> <string name="fragment01">Fragment01</string> <string name="fragment02">Fragment02</string> <string name="click">Click</string> </resources> fragment_fragment01.xmlの内容は以下の通りにする。Buttonを追加し、textを@string/clickに設定する。TextViewのtextを@string/fragment01に設定する。また全体をConstraintLayoutで包み、DataBindingのためにlayoutでさらに包む。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 <?xml version="1.0" encoding="utf-8"?> <layout 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" tools:context=".Fragment01"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text_fragment01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/fragment01" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/click" app:layout_constraintBottom_toTopOf="@+id/text_fragment01" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> </layout> fragment_fragment02.xmlもほぼ同じ。Buttonが無い点だけ異なる。 ...