Android - 有什么方法可以用动画切换 ActionBar 图标吗?

Android - Is there any way to toggle ActionBar icon with animation?

我的应用程序中有一个 DrawerLayoutActionBar 中有一个自定义图标。打开菜单时,图标不可见。再次关闭菜单后,图标会重新出现。现在,它只是 shows\disappears 瞬间。我想为图标添加淡入淡出动画。有什么办法可以达到这个效果吗?

此代码当前用于切换图标:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    if(!drawerOpened){
        inflater.inflate(R.menu.chats_activity_action, menu);
    } else {
        actionBar.setDisplayUseLogoEnabled(false);
    }
    return true;
}

这是在 XML 文件中定义图标的方式:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" >
    <item
        android:id="@+id/menu_filter"
        android:title="Add a user"
        app:showAsAction="always"
        android:icon="@drawable/plus_icon"/>
</menu>

首先,使 MenuItem 在您的布局中不可见:

<item
    android:id="@+id/menu_filter"
    android:title="Add a user"
    app:showAsAction="always"
    android:icon="@drawable/plus_icon"
    android:visible="false"/> <!-- New attribute -->

然后修改你的onCreateOptionsMenu:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    if(!drawerOpened){
        inflater.inflate(R.menu.chats_activity_action, menu);

        final MenuItem item = menu.findItem(R.id.menu_filter);

        // Post delayed so the view can be built,
        // otherwise findViewById(R.id.menu_filter) would be null
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f);
                animation.setDuration(1000);

                // Make item visible and start the animation
                item.setVisible(true);
                findViewById(R.id.menu_filter).startAnimation(animation);
            }
        }, 1);
    } else{
        actionBar.setDisplayUseLogoEnabled(false);


        inflater.inflate(R.menu.chats_activity_action, menu);
        final MenuItem item = menu.findItem(R.id.menu_filter);
        item.setVisible(true);

        // Post delayed so the view can be built,
        // otherwise findViewById(R.id.menu_filter) would be null
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AlphaAnimation animation = new AlphaAnimation(0.1f, 0.0f);
                animation.setFillEnabled(true);
                animation.setFillAfter(true);
                animation.setDuration(1000);

                // start the animation
                findViewById(R.id.menu_filter).startAnimation(animation);
            }
        }, 1);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                item.setVisible(false);
            }
        }, 1000); // The animation is finished after 1000ms
    }
    return true;
 }

基本上,即使抽屉打开,物品也会充气。之后,该项目会随着动画淡出并在动画结束后设置为不可见。