【问题标题】:Android databinding and animationAndroid 数据绑定和动画
【发布时间】:2016-04-02 04:37:23
【问题描述】:

有人可以指出使用数据绑定时如何触发动画的方向吗?

我有一个图标,它会根据我的视图模型中的数据而变化。当 viewmodel 发生变化时(即 viewmodel 中的属性发生变化),如何为图标变化设置动画?

【问题讨论】:

  • 如果您的 viemodel 中的属性发生变化,您想触发动画吗?这是'当视图模型改变'的意思吗?
  • 是的,这正是我的意思。
  • 通过示例添加了答案。

标签: java android mvvm


【解决方案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(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”属性绑定到视图(图像按钮)。 您可以在任何视图中使用此适配器,而不仅仅是在图像按钮上。

当然,“isBusy”属性必须是可绑定的(例如,您的视图模型扩展了 BaseObservable 或至少是 ObservableBoolean)。

因此,每当您将“isBusy”属性更改为 true 时,它​​都会触发动画开始。 设置为false,就停止了。

希望这有帮助吗?

【讨论】:

  • 谢谢。我认为这正是我所需要的。会试一试
  • 如何将 ViewBusyBindings` 与视图模型链接?
  • @tir38,你不需要那个,把@BindingAdapter放在任何地方,然后在xml中使用它,比如app:isBusy="@{vm.isBusy}"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2016-06-19
  • 2015-09-05
  • 2020-09-17
  • 2011-07-20
  • 1970-01-01
相关资源
最近更新 更多