Androidアプリ開発で差をつける!Lottieを使ったアニメーション実装

こんにちわ。昨年(23年末)に開発者登録し、アプリのリリースを始めたzm softです。開発者向けのアプリもリリースを予定していますので、よければご確認ください。

皆さんはアプリ内でアニメーション表示をつかっていますか?少しアニメーションがあるだけでアプリとして分かりやすくなったり見栄えが良くなったりしますよね?そこで、本日は、androidアプリでアニメーション表示をする話を書こうと思います。

LottieAnimation

私が使用しているのは、アニメーション表示ライブラリであるLottieAnimatiinです。比較的簡単に軽量のアニメーション表示ができるので利用しています。

どんなアニメーション表示ができるか/アニメーションの種類

まず、このライブラリでの良い点は、無料で利用できるアニメーションの豊富さです。例えば、以下のようなアニメーションがあります。

このようなアニメーションはLottieFilesの公式サイトで公開されています。有料のアニメーションも多数ありますが、無料に絞って検索をして出てくるものだけでも十分に利用ができます。基本的に私はアニメーションをイチから作るスキルもエネルギーもないため、なにか動きが欲しいときにはまずは、このサイトから使えるものがないかを考えます。例えば、以下のようなアニメーションを使うことで、初回表示時によくあるクリック箇所をユーザーに教えるといった表現ができます。私は実際にこの右側のアニメーションを利用して、ユーザーへの操作案内をするようにしました。

ポイントは手軽さ

実装においてもかなりシンプルに対応できます。例えば、決まったレイアウトにアニメーションを表示するだけであれば、以下のような形で定義するだけで動きます。ロジックの実装をしなくても動作するって良いですよね。 

Lottieの簡単な実装方法

Lottieの実装は非常にシンプルです。特定のレイアウトにアニメーションを埋め込むだけで、追加のロジックなしで動作します。

実装例:

   <com.airbnb.lottie.LottieAnimationView
        android:id="@+id/lottie_id"
        app:lottie_rawRes="@raw/your_lottie_animation"/>

Lottieの基本的な使い方

Lottieの大まかな使い方は以下の通りです。

  • ライブラリの組み込み(build.gradleの修正)
  • アニメーションファイルの取得と配置
  • レイアウトファイルの設定
  • アニメーションのカスタマイズ

具体的な実装例とコード

以下に、Lottieを使用する際の具体的な実装例を提供します。これには、ライブラリの取り込み、アニメーションファイルの配置方法、レイアウトファイルの設定方法、さらにアニメーションのカスタマイズ方法が含まれます。

build.gradleへの記載/ライブラリの取り込み:
まずは、ライブラリ取り込んでlottieを使える状態にします。
特に組み合わせ等の問題がなければ、最新環境を利用してください。

dependencies {
    implementation 'com.airbnb.android:lottie:3.4.0'
}

アニメーションファイルの配置:
LottieFilesの公式サイトから好きなアニメーションファイル(.json)をダウンロードし、アプリのres/rawフォルダに配置します。利用したいアニメーションを見つけて、ワークスペースに保存したうえでダウンロードボタンからダウンロードができます。ダウンロードは、無料ですがユーザー登録が必要になります。配置先は、rawフォルダです。フォルダがない場合には作成してください。また、ファイル名はandroidの命名規則に従う形で任意に変更してください。(規則に従わない場合は、以下のようにエラー表示されます。)

レイアウトファイルの設定:
XMLレイアウトにLottieAnimationViewを追加し、ダウンロードしたアニメーションファイルを参照できるようにします。

アニメーションのカスタマイズ:
必要に応じて、アニメーションの挙動をカスタマイズしてください。アニメーションの設定では、以下のようなことが行えます。

  • ループ再生の有無
  • ループ回数の指定
  • 再生スピードの指定(逆再生を含む)

動的な処理を追加すれば、好きなタイミングで再生/停止をしたり、再生速度を変えたりもできます。

まずは、静的な指定の仕方についてです。それぞれ以下の指定によりアニメーション動作が変わります。

   <com.airbnb.lottie.LottieAnimationView
        android:id="@+id/lottie_id"
        android:scaleType="centerCrop"
        app:lottie_autoPlay="true"
        app:lottie_loop="true"
        app:lottie_speed="0.15" 
        app:lottie_rawRes="@raw/your_lottie_animation"/>

この例では、your_lottie_animation.jsonのファイルを0.15倍の再生速度で自動再生 かつ 繰り返し再生しています。

次に動的な処理です。

lottieAnimationView.playAnimation()

上記処理で再生ができます。再生以外にも設定を変更して停止などスピードを変えたりもできます。以下のようにリスナーをセットし、再生の終了を検知して処理をすることもできます。

        lottieAnimationView.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                // アニメーション開始時の処理
            }

            override fun onAnimationEnd(animation: Animator) {
                // アニメーション終了時の処理
            }

            override fun onAnimationCancel(animation: Animator) {
                // アニメーションがキャンセルされた時の処理
            }

            override fun onAnimationRepeat(animation: Animator) {
                // アニメーションがリピートされる時の処理
            }
        })

注意点とトラブルシューティング

Lottieは非常に便利ですが、いくつかの注意点があります。特に、オブジェクトの位置変更が期待通りに機能しないことがあるようです。また、アニメーション終了時の処理に関するスタックオーバーフローの問題や、onPause後の挙動についても説明します。

トラブルシューティングの例1:
私の実装の問題ですがアニメーション終了時の処理のハンドリングの仕方でスタックオーバーフローを引き起こしました。具体的には、アニメーションの最後までいったときに逆再生し、再生と逆再生を繰り返す用にした処理に問題がありました。再生の終了時に再生方向を変えてplayAnimation()をし直すようにしていたことで再起呼び出しとなり、再生の度にスタックが詰みあがり、アプリが落ちる現象が発生し、PlayStoreでのアップデートを拒絶されてしまいました。以下のようにメインスレッドへのポストとしキューへの積み直しをすることで問題を解決しました。

        lottieAnimationView.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                // アニメーション開始時の処理
            }

            override fun onAnimationEnd(animation: Animator) {
                // アニメーション終了時の処理
                lottieAnimationView.speed = lottieAnimationView.speed*(-1) // 逆再生のためにスピードを逆にする
                lottieAnimationView.post {
                    // 直接呼ぶと再起呼び出しでスタックオーバーフローするのでPOSTする
                    if(isAttachedToWindow) {
                        lottieAnimationView.playAnimation()
                    }
                }
            }

            override fun onAnimationCancel(animation: Animator) {
                // アニメーションがキャンセルされた時の処理
            }

            override fun onAnimationRepeat(animation: Animator) {
                // アニメーションがリピートされる時の処理
            }
        })

トラブルシューティングの例2:
もう一つ気を付けなければならないのはonPause後の処理です。不要な動作をさせないため、バックグラウンドでのanimationを止めるべきでしょう。

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        // アニメーションを開始
        lottieAnimationView.playAnimation()
    }

    override fun onPause(owner: LifecycleOwner) {
        lottieAnimationView.cancelAnimation()
        super.onPause(owner)
    }

しかし、アニメーションの終了時等に処理を行なっている場合には、これだけでは不十分でした。アニメーションの終了とほぼ同時にバックグラウンド回った際の挙動を意識する必要があります。裏でアニメーションをしないように再生を止めたとしても、タイミングによっては裏にまわった後にonAnimationEnd等が走ります。そのため、そのあたりのチェックをせず、UIを触っていたりするとExceptionやアプリが落ちる動作につながります。そこで前述のコードの以下の部分ように、親ビューがデタッチされていないかどうかをチェックし、再処理を行う必要がありました。

                    if(isAttachedToWindow) {
                        binding.lottieBackground.playAnimation()
                    }

まとめ

Lottieは、アプリのUIを向上させるための強力なツールです。無料で利用できるアニメーションが豊富で、実装もシンプルです。注意点を理解し、適切に対処することで、アプリ開発における大きなメリットを享受できます。多少の注意点はありますが全体的に非常に使いやすく、無料で使えるリソースも多いことから素晴らしいライブラリだと思います。アプリの見た目を良くするのに一役買ってくれるのは間違いないと思うので是非お試しください。

「Androidアプリ開発で差をつける!Lottieを使ったアニメーション実装」への216件のフィードバック

  1. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  2. Hello there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank
    for some targeted keywords but I’m not seeing very good success.
    If you know of any please share. Cheers! You can read similar article here: Eco blankets

  3. sugar defender official website For
    years, I have actually fought unpredictable blood glucose swings that left me feeling drained pipes and sluggish.
    Yet considering that incorporating Sugar my power degrees are now stable and regular, and I no
    longer strike a wall in the mid-days. I value that it’s a
    gentle, natural technique that doesn’t included any type of unpleasant negative effects.
    It’s really changed my every day life.

  4. I’m excited to find this great site. I need to to thank you for your time for this fantastic read!! I definitely loved every part of it and i also have you bookmarked to look at new things on your web site.

  5. Oh my goodness! Impressive article dude! Thanks, However I am encountering problems with your RSS. I don’t understand why I cannot join it. Is there anyone else getting similar RSS problems? Anybody who knows the answer can you kindly respond? Thanks!

  6. After I originally commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on each time a comment is added I get four emails with the same comment. There has to be a way you are able to remove me from that service? Many thanks.

  7. After looking into a handful of the blog posts on your blog, I really like your way of blogging. I book marked it to my bookmark site list and will be checking back in the near future. Please check out my web site as well and tell me what you think.

  8. A motivating discussion is definitely worth comment. There’s no doubt that that you should write more on this topic, it may not be a taboo matter but generally people don’t discuss such subjects. To the next! Many thanks.

  9. This is basically a jukebox musical, with selections from The great American Songbook (“Bewitched, Bothered, and Bewildered”) and ‘60s worldwide pop (“To Love Someone,” originated by the Bee Gees and additional popularized by Janis Joplin) and more.

  10. After looking at a handful of the blog articles on your web page, I really like your way of writing a blog. I bookmarked it to my bookmark site list and will be checking back soon. Please check out my website as well and let me know your opinion.

  11. A house is where you lived in 2023 and might embody a house, houseboat, cell residence, cooperative residence, condominium, and a manufactured house that conforms to Federal Manufactured Residence Development and Safety Standards.

  12. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  13. You have made some really good points there. I checked on the web to learn more about the issue and found most individuals will go along with your views on this website.

  14. You’re so interesting! I do not think I have read through a single thing like that before. So wonderful to find another person with some original thoughts on this issue. Seriously.. thanks for starting this up. This site is one thing that is needed on the internet, someone with some originality.

  15. I would like to thank you for the efforts you’ve put in penning this blog. I really hope to see the same high-grade blog posts by you in the future as well. In fact, your creative writing abilities has encouraged me to get my own, personal website now 😉

  16. Nice post. I learn something totally new and challenging on sites I stumbleupon everyday. It’s always helpful to read through articles from other writers and use a little something from their websites.

  17. You’re so interesting! I do not suppose I have read something like this before. So good to find someone with genuine thoughts on this subject matter. Really.. thank you for starting this up. This web site is one thing that’s needed on the web, someone with a bit of originality.

  18. When I originally commented I appear to have clicked the -Notify me when new comments are added- checkbox and from now on every time a comment is added I receive 4 emails with the exact same comment. Perhaps there is a way you are able to remove me from that service? Thanks.

  19. I really love your blog.. Pleasant colors & theme. Did you build this web site yourself? Please reply back as I’m trying to create my very own site and want to learn where you got this from or just what the theme is named. Thanks.

  20. That is a very good tip particularly to those new to the blogosphere. Simple but very accurate info… Thank you for sharing this one. A must read post.

  21. Can I just say what a comfort to uncover somebody that really understands what they’re discussing over the internet. You definitely realize how to bring a problem to light and make it important. More people should check this out and understand this side of your story. It’s surprising you’re not more popular because you definitely have the gift.

  22. I really love your website.. Great colors & theme. Did you create this site yourself? Please reply back as I’m hoping to create my own blog and want to learn where you got this from or exactly what the theme is named. Many thanks.

  23. Having read this I thought it was really informative. I appreciate you finding the time and energy to put this information together. I once again find myself personally spending way too much time both reading and posting comments. But so what, it was still worth it.

  24. Howdy, I think your site might be having browser compatibility problems. Whenever I take a look at your website in Safari, it looks fine however when opening in IE, it’s got some overlapping issues. I merely wanted to give you a quick heads up! Besides that, fantastic website.

  25. An intriguing discussion is definitely worth comment. I believe that you need to publish more on this subject matter, it may not be a taboo subject but typically folks don’t discuss these issues. To the next! Cheers!

  26. Having read this I believed it was very informative. I appreciate you finding the time and effort to put this short article together. I once again find myself personally spending a lot of time both reading and posting comments. But so what, it was still worthwhile.

  27. Having read this I believed it was rather informative. I appreciate you taking the time and energy to put this short article together. I once again find myself spending a lot of time both reading and posting comments. But so what, it was still worth it!

  28. Hello there! I could have sworn I’ve visited this web site before but after going through a few of the posts I realized it’s new to me. Nonetheless, I’m definitely happy I stumbled upon it and I’ll be bookmarking it and checking back often!

  29. This is a really good tip especially to those fresh to the blogosphere. Brief but very accurate info… Appreciate your sharing this one. A must read article!

  30. When I initially left a comment I appear to have clicked the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I recieve four emails with the same comment. Is there an easy method you can remove me from that service? Thanks a lot.

  31. Having read this I believed it was extremely informative. I appreciate you taking the time and energy to put this short article together. I once again find myself spending way too much time both reading and posting comments. But so what, it was still worthwhile.

  32. NL Pitchero studies that “The Board of Administrators at Vanarama National League North membership FC United of Manchester thought fans would like to share our frustration and bemusement on the request it obtained on Friday from the BBC, through the FA, to maneuver the kick off time of their Emirates FA Cup sport towards Sporting Khalsa to allow a ‘model new BBC Cell Match of The Day Dwell experience’. This newest concept included disruption to the pre-match preparations of club volunteers and the competing teams, interruptions to substitutes warming up and interference with the workforce managers’ match management. The FC United Board gave a resounding ‘NO’ to this request. Match-going supporters should not should be inconvenienced for the advantage of those who not often, if at all, attend matches. FC United will not be intrinsically opposed to the re-association of a fixture time, offered that it meets with the approval of and advantages the respective clubs and their supporters. In 2007, members of FC United voted in favour of entering the FA Cup and acknowledged the competitions rules and Television contracts. That apart, the entire ‘Cellular Match of The Day Stay experience’ ought to have been canned at inception by any BBC Sports supervisor with an understanding of the sport. As a public service broadcaster the BBC ought to be taking a lead by selling the sport with out causing further disruption to match going supporters as a substitute of attempting to ape or outdo some of the worst excesses of their opponents. If BBC viewers would like to know the fans’ experience at a football sport there are quite a few real-life games at every degree all through the country and the easiest way for Television viewers to entry the real fans’ expertise is to go alongside to a match. For a more in depth experience they could volunteer like many non-League followers do week in and week out. The Board acknowledged further, ‘The FA, as the governing physique of football on this nation, appear to be encouraging methods to money in on the fans’ expertise whilst treating the supporters because the least necessary commodity in the sport. We name upon the FA to do not forget that soccer is a sporting competition and the associated drama comes from the highs and lows of the sport itself. It does not replicate nicely on the custodians of our recreation that they might devalue the sporting integrity of their flagship competition by encouraging Tv presenters to interfere with those within the dug-outs or altering rooms when they are working to supply the perfect competitive elements of the game. Nor ought to Television have entry to substitutes when warming up, as a result of these players are athletes preparing properly to have the ability to compete at their best. Television exposure and the revenue it generates are necessary to soccer. Nevertheless, we consider that the steadiness has swung approach too far in favour of the Television firms and too far away from the match-going, admission paying, regularly attending soccer supporter. “FC United seeks to vary the way that soccer is owned and run, putting supporters at the guts of everything.

  33. You’re so interesting! I do not think I’ve read something like this before. So great to find another person with genuine thoughts on this subject. Really.. thanks for starting this up. This web site is something that is needed on the web, someone with a little originality.

  34. You have made some decent points there. I checked on the web to find out more about the issue and found most people will go along with your views on this website.

  35. Bridal attire: Tamil brides are normally spotted carrying a 9-yard or a six-yard Kanjivaram saree in vibrant hues with contrasting borders that have exquisite patterns woven in golden threads as their wedding ceremony outfits.

  36. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  37. Can I just say what a relief to find a person that truly understands what they are discussing online. You certainly understand how to bring an issue to light and make it important. A lot more people really need to look at this and understand this side of your story. I was surprised that you aren’t more popular given that you most certainly possess the gift.

  38. You’ve made some decent points there. I looked on the net to find out more about the issue and found most people will go along with your views on this website.

  39. However, the saying “they do not make ’em like they used to” typically applies right here, so you could also be pleased to find that your antique requires just some days in the shop to run like new again.

  40. I must thank you for the efforts you have put in writing this site. I really hope to check out the same high-grade content by you in the future as well. In fact, your creative writing abilities has encouraged me to get my own, personal website now 😉

  41. After going over a few of the blog articles on your website, I honestly like your way of blogging. I saved it to my bookmark site list and will be checking back soon. Please check out my web site too and tell me your opinion.

  42. Right here is the perfect blog for anyone who would like to find out about this topic. You know so much its almost hard to argue with you (not that I personally would want to…HaHa). You certainly put a brand new spin on a topic that has been written about for a long time. Excellent stuff, just great.

  43. However, what is termed as event driven investing in financial circles has to do more with what is not known by common people like the pricing opportunities that may take place before an earnings call or merger, or the inefficiencies that are bound to occur after a bankruptcy or spinoff.

  44. Hello! I simply want to give you a big thumbs up for the great info you’ve got right here on this post. I will be returning to your blog for more soon.

  45. Oh my goodness! Awesome article dude! Thank you so much, However I am going through issues with your RSS. I don’t understand why I am unable to subscribe to it. Is there anybody else having similar RSS problems? Anyone who knows the solution will you kindly respond? Thanx!

  46. Hello! I could have sworn I’ve been to this web site before but after looking at many of the articles I realized it’s new to me. Nonetheless, I’m certainly delighted I discovered it and I’ll be book-marking it and checking back frequently!

  47. An outstanding share! I’ve just forwarded this onto a colleague who has been doing a little homework on this. And he in fact bought me lunch simply because I stumbled upon it for him… lol. So let me reword this…. Thank YOU for the meal!! But yeah, thanks for spending the time to talk about this topic here on your website.

  48. Within the late 1880s, its African-American and poor white populations have been affected by modifications to laws by the state legislature, which made voter registration and voting more difficult by requirements together with imposition of a poll tax in 1889.

  49. Rubenstein’s fears would be confirmed when in 2007, the Service Employees International Union launched a campaign against private equity firms, specifically the largest buyout firms through public events, protests as well as leafleting and web campaigns.

  50. I’m very pleased to discover this site. I want to to thank you for your time just for this wonderful read!! I definitely savored every little bit of it and I have you saved to fav to see new stuff in your site.

  51. When I initially left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I get 4 emails with the same comment. Perhaps there is a way you can remove me from that service? Many thanks.

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

上部へスクロール