2015-12-28 7 views
8

データバインディングを使用しているときに、アニメーションをトリガする方法の方向に私を指摘できますか?Androidのデータバインディングとアニメーション

私のビューモデル内のデータに応じて変化するアイコンがあります。ビューモデルが変更されたとき(つまり、プロパティがビューモデル内で変更されたとき)にアイコンのアニメーションを変更するにはどうすればよいですか?

+0

viemodelでプロパティが変更された場合はアニメーションをトリガーしますか?これは「ビューモデルが変わるとき」の意味ですか? –

+0

はい、それはまさに私の意味です。 –

+0

例に答えを加えました。 –

答えて

15

解決策の1つは、結合アダプターを使用することです。

まず我々はカスタムバインディングアダプタを定義します: はここであなたを移動するための方法を示すために、迅速なサンプルだ

import android.databinding.BindingAdapter; 
import android.support.v4.view.animation.FastOutSlowInInterpolator; 
import android.view.View; 
import android.view.animation.Animation; 
import android.view.animation.Interpolator; 
import android.view.animation.RotateAnimation; 
import android.view.animation.TranslateAnimation; 

public class ViewBusyBindings { 
    private static final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator(); 

    @BindingAdapter("isBusy") 
    public static void setIsBusy(View view, boolean isBusy) { 
     Animation animation = view.getAnimation(); 
     if (isBusy && animation == null) { 
      view.startAnimation(getAnimation()); 
     } else if (animation != null) { 
      animation.cancel(); 
      view.setAnimation(null); 
     } 
    } 

    private static Animation getAnimation() { 
     RotateAnimation anim = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); 
     anim.setInterpolator(INTERPOLATOR); 
     anim.setDuration(1400); 
     anim.setRepeatCount(TranslateAnimation.INFINITE); 
     anim.setRepeatMode(TranslateAnimation.RESTART); 
     return anim; 

    } 
} 

レイアウト例は次のようになります。

<?xml version="1.0" encoding="utf-8"?> 
<layout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:app="http://schemas.android.com/apk/res-auto"> 
    <data> 
     <variable 
      name="vm" 
      type="de.example.exampleviewmodel"/> 
    </data> 

    <FrameLayout 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       > 
     <ImageButton 
      android:id="@+id/btnPlay" 
      style="?attr/borderlessButtonStyle" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="right|bottom" 
      android:src="@drawable/ic_play_circle_filled_white_36dp" 
      app:isBusy="@{vm.isBusy}"/> 

    </FrameLayout> 
</layout> 

することができますようにあなたのviemodelの 'isBusy'プロパティは、ビュー(imagebutton)にバインドされています。 このアダプターは、画像ボタンだけでなく、どのビューでも使用できます。

もちろん、isBusyプロパティはバインド可能でなければなりません(たとえば、ビューモデルがBaseObservableを拡張するか、ObservableBoolean以上であるなど)。

したがって、 'isBusy'プロパティをtrueに変更すると、アニメーションが開始されます。 falseに設定すると停止します。

希望すると便利ですか?

+0

ありがとうございます。私はこれがまさに私が必要なものだと思う。それを試してみる –

+0

それはあまりにもドープだ! – sirvon

+0

ViewBusyBindings'をビューモデルとどのようにリンクしますか? – tir38

関連する問題