[英]Android - Is there any way to toggle ActionBar icon with animation?
我的应用程序中有一个DrawerLayout
, ActionBar
有一个自定义图标。 打开菜单时,图标不可见。 菜单再次关闭后,图标会重新显示。 现在,它只是显示\\立即消失。 我想在图标中添加淡入淡出动画。 有没有办法达到这个效果?
此代码目前用于切换图标:
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;
}
基本上,即使抽屉打开,物品也会膨胀。 之后,该项目随着动画逐渐消失,并在动画结束后设置为不可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.