LoginSignup
9
3

More than 3 years have passed since last update.

recyclerview-animatorsを使ってみて

Last updated at Posted at 2019-10-24

はじめに

現在開発しているAndroidアプリでRecyclerViewを使用しており、
そこにアニメーションをつけるときに発見しました。

recyclerview-animatorsとは

recyclerview-animatorsは、RecyclerViewのitemにアニメーションをつけるものです。
これを使うことにより、RecyclerViewにitemを追加や削除したときに、様々なアニメーションをつけることができます。

使用方法

1.build.gradleにrecyclerview-animatorsのimplementationを追加
2.使用したいアニメーションをRecyclerViewにセット
3.RecyclerViewにitem追加と削除の処理を書く

の3ステップで使用できます。

1. build.gradleにrecyclerview-animatorsのimplementationを追加

まず、build.gradleに

build.gradle
dependencies {
    implementation 'jp.wasabeef:recyclerview-animators:3.0.0'
}

を追加します。

2. 使用したいアニメーションをRecyclerViewにセット

build.gradleに追加が終わったら、RecyclerViewのitemAnimatorに動作させたいアニメーションを記述します。

MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
    recyclerView.itemAnimator = SlideInLeftAnimator() // 左からスライドAnimationが実行される
}

3. RecyclerViewにitem追加と削除の処理を書く

最後に、RecyclerViewにitemを追加と削除するときの処理を記述します。
今回はGroupieを使用しているため、以下のように書きました。

MainActivity.kt
    private val groupAdapter = GroupAdapter<ViewHolder>()

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

        recyclerView.apply {
            adapter = groupAdapter
            itemAnimator = SlideInLeftAnimator(DecelerateInterpolator(0.1f))
            layoutManager = LinearLayoutManager(context)
        }
        create.setOnClickListener {
            groupAdapter.add(Item(groupAdapter.itemCount.toString()))
            groupAdapter.notifyItemChanged(groupAdapter.itemCount)
        }

        delete.setOnClickListener {
            if (groupAdapter.itemCount < 1) {
                return@setOnClickListener
            }
            groupAdapter.removeGroup(groupAdapter.itemCount - 1)
            groupAdapter.notifyItemChanged(groupAdapter.itemCount - 1)
        }
    }

このように書くことでアニメーションが動作します!

スライドイン スライドアウト
SlideInLeftAnimator.gif SlideOutLeftAnimator.gif

他にもフェードイン・アウトアニメーションやフリップアニメーション、
また動作方向やアニメーション変化を変更することができるみたいです。

まとめ

アニメーションをつけることは本来難しいのですが、とても簡単に実装できるため、
これから使っていこうと思いました。

9
3
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
9
3