有人能指出我在使用数据绑定时如何触发动画的方向吗?
我有一个图标,根据我的viewmodel中的数据进行更改。如何在视图模型更改时(即,视图模型中的属性发生更改时)动画图标更改?
答案 0 :(得分:18)
一种可能的解决方案是使用绑定适配器。 这是一个快速示例,向您展示如何前进:
首先我们定义一个自定义绑定适配器:
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(createAnimation());
} else if (animation != null) {
animation.cancel();
view.setAnimation(null);
}
}
private static Animation createAnimation() {
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'属性必须是可绑定的(例如,你的viewmodel扩展了BaseObservable或者至少它是一个ObservableBoolean)。
因此,每当您将'isBusy'属性更改为true时,它都会触发动画启动。 将其设置为false,它会停止。
希望这有帮助吗?