Android: how to make animation transition to toolbar menu icons?

If you use the latest version of WhatsApp, you will notice that if you long press the text field in the chat, the menu icons on the toolbar will change with a nice rotating animation.

How can I reproduce this effect? I know that I have to invalidate the menu, but not how to make the animation.

+4
source share
1 answer
  • Use Toolbar.
  • Wait until the toolbar is full.
  • Find this item
  • Element animation

Example:

mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom,
                               int oldLeft, int oldTop, int oldRight, int oldBottom) {
        View item = mToolbar.findViewById(R.id.action_add_item);
        if (item != null) {
            mToolbar.removeOnLayoutChangeListener(this);
            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ObjectAnimator animator = ObjectAnimator
                            .ofFloat(v, "rotation", v.getRotation() + 180);
                    animator.start();
                }
            });
        }
    }
});

A note R.id.action_add_itemis an attribute id MenuItem.

+17
source

All Articles