Search code examples
androidanimationmenurotationmenuitem

Menu item animation, rotate indefinitely its custom icon


I have a menu item with an icon (imagine for example a clock with a single lancet), I would like to make its icon rotate indefinitely.

How could I manage this effect? Thank you.


Solution

  • Add a file res/layout/iv_refresh.xml (replace ic_launcher with your custom icon):

    <?xml version="1.0" encoding="utf-8"?>
    <ImageView
        xmlns:android="http://schemas.android.com/apk/res/android"
        style="@android:style/Widget.ActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/app_name"
        android:src="@drawable/ic_launcher" />
    

    Add a file res/anim/rotate_refresh.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="1000"
        android:fromDegrees="0"
        android:interpolator="@android:anim/linear_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="360">
    </rotate>
    

    Finally in your java code you can start the animation like this:

    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
    Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
    rotation.setRepeatCount(Animation.INFINITE);
    iv.startAnimation(rotation);
    menu.findItem(R.id.my_menu_item_id).setActionView(iv);