LoginSignup
15
17

More than 5 years have passed since last update.

Androidでいい感じのインタラクションが得られるアニメーションライブラリ(by Kotlin)

Last updated at Posted at 2016-03-16

を公開しました。

kidach1/AndroidSwayAnimation
https://github.com/kidach1/AndroidSwayAnimation

SwayAnim2.gif

gifだといまいちに見えるので別途動画を。

Sample / Sample with RecyclerView

Download

build.gradle
dependencies {
    compile 'com.kidach1:AndroidSwayAnimation:1.0.8'
}

Usage

SwayAnimation.ready()に対してアニメーション表示領域(animatedZone)とタッチ領域(touchZone)、Contextを渡すだけです。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RelativeLayout animatedZone = (RelativeLayout) findViewById(R.id.animatedLayout);
    RelativeLayout touchZone = (RelativeLayout) findViewById(R.id.touchedLayout);
    SwayAnimation.ready(animatedZone, touchZone, this);
}

アニメーション素材のカスタマイズ

SwayAnimation.setDrawables(Arrays.asList(
        R.drawable.ic_favorite_pink_300_48dp,
        R.drawable.ic_tag_faces_amber_300_48dp,
        R.drawable.ic_thumb_up_blue_a200_48dp
));
SwayAnimation.ready(animatedZone, touchZone, this);

Kotlin関連

基本的にさくさく書けましたが、2点ほど。

(Javaからアクセス可能な)staticメソッド

  • staticメソッドにはcompanion object
  • Javaからもアクセス可能にするために@JvmStatic
class SwayAnimation {
    companion object {
        @JvmStatic fun ready(animatedZone: ViewGroup, ...) {
            touchedZone.setOnTouchListener { v, event ->
              // ...
            }
        }
    }
}

Calling Kotlin from Java - Kotlin Programming Language
https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-methods

Backing Fields

kotlinはsetter/getterを内部的に自動生成してくれる。例えばwithActionBarというフィールドが存在する時、以下のように一見直接フィールドにアクセスするような書き方でも、実際はsetter経由になっている。

withActionBar = true

よって、自分でsetterを定義したい際に

// @JvmStaticを付与するためにカスタムsetterを定義
var withActionBar: Boolean = false
    @JvmStatic set(bool) {
        withActionBar = bool
    }

と書いてしまうと、setterを再帰的に無限に呼び出し続けることになりStackOverFlowが発生する。

この解決策として、Backing Fieldsと呼ばれる特別なフィールドを用います。
といっても簡単で、代入先をfieldというidentifierに変えてやるだけ。

var withActionBar: Boolean = false
    @JvmStatic set(bool) {
        field = bool
    }

Properties and Fields - Kotlin Programming Language
https://kotlinlang.org/docs/reference/properties.html#backing-fields

まとめ

kotlinは良いものだ

15
17
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
15
17