【Kotlin】下部ナビゲーション・アクティビティを触ってみる

最近のアプリには必ずと言ってもいいほど存在する下部ナビゲーション
AndroidStudioにはテンプレとして存在するからお試しに使ってみる

![スクリーンショット 2020-05-03 17.30.54.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/283826/3d5d6aa9-e396-4ebc-569f-f34d74041c99.png)

#作ったらこんなの入ってた

![スクリーンショット 2020-05-03 17.33.42.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/283826/64accb3b-a1de-aeee-625a-9de9e0fc2ec4.png)

そのまま起動しても↓の感じで使える

![スクリーンショット 2020-05-03 17.40.40.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/283826/2952040c-91dc-630c-e470-d0b93e1841b2.png)
![スクリーンショット 2020-05-03 17.40.53.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/283826/ba161ea2-4f61-87e8-350b-f271911a1281.png)
![スクリーンショット 2020-05-03 17.41.03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/283826/d53e75a8-eb3f-e624-8d03-14fb5b4c2d00.png)

##ソース読んでみる
###Main

```kotlin:MainActivity.kt
package com.navsample

import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navView: BottomNavigationView = findViewById(R.id.nav_view)

        val navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        val appBarConfiguration = AppBarConfiguration(setOf(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications))
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
    }
}
```

```xml:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        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_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

![スクリーンショット 2020-05-03 17.32.58.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/283826/d16b4c43-2458-cba8-6b44-1135a8fe0083.png)


MainActivityは司令塔。
他のフラグメント（Home、Dashboard、Notifications）を制御している。

```kotlin

        val navView: BottomNavigationView = findViewById(R.id.nav_view)
        val navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        val appBarConfiguration = AppBarConfiguration(setOf(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications))
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
```

下部ナビゲーションのレイアウトID(nav_viewとnav_host_fragment)を設定。
vav_viewは下部ナビゲーションのところ。
nav_host_fragmentがメイン画面のフラグメントの部分（下部ナビゲーションをタッチすると変わるところ）
appBarConfigurationはなんかコメントがついてるからその通りにやってみればいいのかな

###Home

```kotlin:HomeFragment.kt
package com.navsample.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.navsample.R

class HomeFragment : Fragment() {

    private lateinit var homeViewModel: HomeViewModel

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        val textView: TextView = root.findViewById(R.id.text_home)
        homeViewModel.text.observe(viewLifecycleOwner, Observer {
            textView.text = it
        })
        return root
    }
}

```

```kotlin:HomeViewModel.kt
package com.navsample.ui.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class HomeViewModel : ViewModel() {

    private val _text = MutableLiveData<String>().apply {
        value = "This is home Fragment"
    }
    val text: LiveData<String> = _text
}
```
<img width="933" alt="スクリーンショット 2020-05-03 23.32.34.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/283826/1b74896d-e50f-5e28-220f-5ccde5c6633b.png">

```xml:fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".ui.home.HomeFragment">

    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
```

あとはフラグメントの話。
残り二つもほとんど一緒。