为标题栏菜单项添加动画效果,需要设置菜单的 actionView
,并且给 actionView
设置动画。点击菜单时开始动画,完成菜单项对应的功能后停止动画。
菜单项的 actionView
:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/Widget.AppCompat.ActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_refresh_white_24dp">
</ImageView>
旋转动画:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1000"
android:interpolator="@android:anim/linear_interpolator">
</rotate>
模拟延时动画效果
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.item_rotate, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh: {
mRefreshItem = item;
refresh();
return true;
}
}
return super.onOptionsItemSelected(item);
}
private void refresh() {
if (getActivity() == null) {
return;
}
ImageView imageView = (ImageView) getActivity().getLayoutInflater()
.inflate(R.layout.action_view_refresh, null);
Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.clockwise_refresh);
animation.setRepeatCount(Animation.INFINITE);
imageView.startAnimation(animation);
mRefreshItem.setActionView(imageView);
new Thread() {
@Override
public void run() {
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
getView().post(new Runnable() {
@Override
public void run() {
mRefreshItem.getActionView().clearAnimation();
mRefreshItem.setActionView(null);
}
});
}
}
}.start();
}
注意最后要移除动画 clearAnimation()
,设置 actionView
为 null
。