Android: 如何在工具栏的菜单图标上制作过渡动画?

Android: how to make transition animations on toolbar's menu icons?

如果您使用最新版本的 WhatsApp,您会注意到,如果您在聊天中长按文本框,工具栏上的菜单图标会随着漂亮的旋转动画而变化。

我怎样才能重现这种效果?我知道我应该使菜单无效,而不是如何制作动画。

  1. 使用 Toolbar.
  2. 等待工具栏的项目膨胀。
  3. 找到有问题的项目
  4. 为项目设置动画

示例:

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();
                }
            });
        }
    }
});

注意 R.id.action_add_itemMenuItemid 属性。