を公開しました。
kidach1/AndroidSwayAnimation
https://github.com/kidach1/AndroidSwayAnimation
gifだといまいちに見えるので別途動画を。
Sample / Sample with RecyclerView
Download
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は良いものだ