Eine mögliche Lösung ist die Verwendung eines Bindungsadapters. Hier ist eine schnelle Probe Ihnen den Weg zu zeigen, zu gehen:
Zuerst haben wir eine benutzerdefinierte Bindung Adapter definieren:
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;
}
}
Das Beispiel Layout wird wie folgt aussehen:
<?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>
Wie Sie können sehen Sie, die Eigenschaft 'isBusy' Ihres Vieodels ist an die Ansicht gebunden (imagebutton). Sie können diesen Adapter in jeder Ansicht nicht nur auf einer Bildschaltfläche verwenden.
Natürlich muss die Eigenschaft 'isBusy' bindbar sein (z. B. erweitert Ihr Viewmodel BaseObservable oder minimal ist es ein ObservableBoolean).
Wenn Sie also die Eigenschaft 'isBusy' auf 'true' setzen, wird die Animation ausgelöst. Setzen Sie es auf false, es stoppt.
Hoffe das hilft?
Sie möchten eine Animation auslösen, wenn sich eine Eigenschaft in Ihrem Videomodel ändert? Ist das die Bedeutung von "wenn sich das Viewmodel ändert"? –
ja, genau das meine ich. –
Antwort mit Beispiel hinzugefügt. –