10
8

More than 1 year has passed since last update.

CoordinatorLayoutをやってみた

Last updated at Posted at 2020-01-07

はじめに

今回はCoordinatorLayoutを使用し、下記のようなスクロールでツールバー等を見え隠れさせるアプリを作成してみました。

実際に実装してみた

上記のアプリの実際のコードはこちらになります。

MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Adapterの設定
        val sampleList = mutableListOf<String>()
        for (i in 0..20) {
            sampleList.add(i.toString())
        }
        val adapter = RecyclerAdapter(sampleList)
        recycler_view.adapter = adapter

        // 区切り線の表示
        recycler_view.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
    }
}
activity_main.xml
<RelativeLayout
    ...
    >

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <androidx.appcompat.widget.Toolbar
                ...
                app:layout_scrollFlags="scroll|enterAlwaysCollapsed" />

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

        <androidx.recyclerview.widget.RecyclerView
            ...
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</RelativeLayout>

実装する際のポイント

上記のようなアプリを実装するためには、いくつかのポイントがあります。
1.CoordinatorLayoutでスクロール時に隠すためには、スクロールする部分がNestedScrollViewRecyclerViewでないといけません。
2.隠したい部分はAppBarLayoutの中に配置し、app:layout_scrollFlagsを使用することで、隠れてくれます。
 app:layout_scrollFlagsには色々な種類がありますが、ここでは割愛します。
上記のアプリを図で表して見ると、こんな感じになります。

3.RecyclerViewlayout_behaviorがないと、AppBarLayoutRecyclerViewが重なって表示されてしまいます。

4.下記の画像の場合、隠したくないものはAppBarLayoutより上位の階位に書く必要があります。
 

おわりに

今回はCoordinatorLayoutを使用し、スクロールでツールバー等を見え隠れさせるアプリを作成してみました。
実装する中で、私が迷ったことや必要なポイントをまとめてみました。
皆さんのお役に立てれば幸いです。

 

10
8
0

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
10
8