有人可以指导我如何在使用数据绑定时触发动画吗?
我有一个图标,根据视图模型中的数据更改。当视图模型更改(即视图模型中的属性更改)时,如何动画化图标更改?
一种可能的解决方案是使用绑定适配器。下面是一个快速示例,为您展示如何操作:
首先,我们定义一个自定义绑定适配器:
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>
正如您所看到的,您的视图模型的“isBusy”属性与视图(imagebutton)绑定。
您可以将此适配器用于任何视图,而不仅仅是imagebutton。
当然,“isBusy”属性必须可绑定(例如,您的视图模型扩展了BaseObservable或者至少是一个ObservableBoolean)。
因此,每当您将“isBusy”属性更改为true时,它将触发动画开始。将其设置为false,则停止。
希望这有所帮助?