Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to use ObjectAnimator in XML

I simply want to use an objectAnimator which is defined in a XML-file. I want to put two objectAnimators and want to choose in my Code which I want to use.

This is how my XML-File looks like where I set the propertyName, that I wanna access later on in the code:

<?xml version"1.0" encodin="utf-8"?>
<set xmlns:android="..."
    <objectAnimator
        android:propertyName="animX"
        android:duration="1000"
        android:valueFrom="FFFFFF"
        android:valueTo="FF0000" />

    <objectAnimator
        android:propertyName="animY"
        android:duration="1000"
        android:valueFrom="FF0000"
        android:valueTo="FFFFFF" />

</set>

That is the code, where I want to access to a propertyName defined objectAnimator:

ObjectAnimator anim = ObjectAnimator.ofFloat(view, "animX");
anim.setTarget(anim);
anim.start();

Unfortunately, that is not how it works and I am really struggling to find a solution to access the objectAnimators I want.

like image 784
csnewb Avatar asked Sep 06 '25 03:09

csnewb


2 Answers

One of two things are the issue:

1) each ObjectAnimator needs to be it's own and then added to a set after you inflate the animator (via final ObjectAnimator animator = (ObjectAnimator) AnimatorInflater.loadAnimator(context, resID);) and set it on the view

2) If the XML is giving you IDE errors, check that your ObjectAnimators are in the /animator folder and not the /anim folder in the /res directory

Edited: /animators was not recognized, but /animator was

like image 155
AllDayAmazing Avatar answered Sep 07 '25 22:09

AllDayAmazing


Instead of putting 2 ObjectAnimators in your XML file, you could rather use PropertyValuesHolder and wrap them in one ObjectAnimator like this:

<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="5000"
    android:interpolator="@android:interpolator/linear"
    android:repeatCount="1"
    android:repeatMode="reverse">

    <propertyValuesHolder
        android:propertyName="scaleX"
        android:valueFrom="1"
        android:valueTo="2" />

    <propertyValuesHolder
        android:propertyName="scaleY"
        android:valueFrom="1"
        android:valueTo="2" />

</objectAnimator>
    

Then you can retrieve this animation like this:

val scaleAnimation = AnimatorInflater.loadAnimator(
        context, R.animator.your_anim_file_name)
scaleAnimation.setTarget('your_view')
scaleAnimation.start()

Or if you have multiple animations like this, you can add them in AnimatorSet and play sequentially or together.

val animatorSet = AnimatorSet()
animatorSet.playSequentially(scaleAnimation, translateAnimation)
animatorSet.start()
like image 43
Hayk Mkrtchyan Avatar answered Sep 07 '25 22:09

Hayk Mkrtchyan