According to the Android developer site, we can load AnimatorSet
class programatically from xml file located on the path like this: res/animator/filename.xml
. So I have created a sample project and tried to see if it actually works, and it doesn't; nothing happens. It would be very nice if I can understand what is missing and/or what I have done wrong. Thanks in advance! Below is my animator xml file and Java code to load the xml:
res/animator/sample.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:ordering="sequentially"
>
<set>
<objectAnimator
android:propertyName="x"
android:duration="500"
android:valueTo="400"
android:valueType="intType"
/>
<objectAnimator
android:propertyName="y"
android:duration="500"
android:valueTo="300"
android:valueType="intType"
/>
</set>
<objectAnimator
android:propertyName="alpha"
android:duration="500"
android:valueTo="1f"
/>
</set>
And here is my Java codes to load the xml file above:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
// Load and start Animaton
AnimatorSet animSet =
(AnimatorSet) AnimatorInflater.loadAnimator(view.getContext(), R.animator.sample);
animSet.setTarget(view);
animSet.start();
}
});
You set contains another Set res/animator/sample.xml
. Simplify it
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:ordering="sequentially"
>
<objectAnimator
android:propertyName="alpha"
android:duration="500"
android:valueTo="1f"
/>
</set>
You inflate the AnimatorSet like this
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(getActivity(), R.animator.sample);
set.setTarget(fab); // set the view you want to animate
set.start();
So far, I haven't found a way to inflate objectAnimator from xml to Java. I have to wrap it inside a Set
This is an error in the example given in the documentation.
Try changing the android:valueType="intType"
to android:valueType="floatType"
.
It works in case of @RaymondChenon as he is not explicitly changing the
android:valueType
to int
so system is taking the default one float
The problem here is you are giving android:valueType="intType"
in your animator which is supposed to be android:valueType="floatType"
for the property android:propertyName="x"
you are animating.
At runtime system look for setter for the property, you want to animate.
Like in your case it will look for setX()
, but as you are defining argument type of type int
it causes a mismatch as there is no such method, I don't know why it doesn't lead to a crash.
Look at the properties of View class there is a method setX(float)
For further understanding, you can refer StackOverflow Question
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With