Java Android数据绑定和动画
有人能告诉我在使用数据绑定时如何触发动画吗Java Android数据绑定和动画,java,android,mvvm,Java,Android,Mvvm,有人能告诉我在使用数据绑定时如何触发动画吗 我有一个图标,它会根据viewmodel中的数据而变化。如何在viewmodel更改(即viewmodel中的属性更改)时设置图标更改的动画?一种可能的解决方案是使用绑定适配器。 下面是一个快速示例,向您展示该方法: 首先,我们定义一个自定义绑定适配器: import android.databinding.BindingAdapter; import android.support.v4.view.animation.FastOutSlowInInt
我有一个图标,它会根据viewmodel中的数据而变化。如何在viewmodel更改(即viewmodel中的属性更改)时设置图标更改的动画?一种可能的解决方案是使用绑定适配器。 下面是一个快速示例,向您展示该方法: 首先,我们定义一个自定义绑定适配器:
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)。
您可以在任何视图中使用此适配器,而不仅仅是在imagebutton上
当然,“isBusy”属性必须是可绑定的(例如,您的viewmodel扩展了BaseObservable,或者至少是ObservableBolean)
因此,无论何时将“isBusy”属性更改为true,它都会触发动画开始。
如果将其设置为false,它将停止
希望这有所帮助?如果模型中的属性发生更改,是否要触发动画?这就是“当视图模型改变”的意思吗?是的,这正是我的意思。用例子补充答案。谢谢。我想这正是我需要的。将尝试如何将ViewBusyBindings`与视图模型链接?@tir38,您不需要它,将@BindingAdapter放在任何位置,然后在类似于xml的应用程序中使用它:isBusy=“@{vm.isBusy}”