Android - 有没有办法用动画切换ActionBar图标?

时间:2015-04-07 13:44:29

标签: android animation android-actionbar android-actionbar-compat

我的应用中有DrawerLayoutActionBar中有自定义图标。打开菜单时,图标不可见。菜单再次关闭后,图标会重新显示。现在,它只是显示\立即消失。我想在图标中添加淡入淡出动画。有没有办法达到这个效果?

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

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>

1 个答案:

答案 0 :(得分:3)

首先,在布局中隐藏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;
 }

基本上,即使抽屉打开,物品也会膨胀。之后,该项目随着动画逐渐消失,并在动画结束后设置为不可见。