actionbar 上的菜单按钮加动画

找了一会,好像只有这一种解决方案。

远离就是在菜单按钮上,添加一层布局,然后在这一层布局上试用动画

代码:

public void setRefreshActionButtonState(final boolean refreshing) {
        if (optionsMenu != null) {
            final MenuItem refreshItem = optionsMenu
                    .findItem(R.id.action_refresh);
            if (refreshItem != null) {
                if (refreshing) {
                    LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    ImageView iv = (ImageView) inflater.inflate(R.layout.actionbar_flushing, null);
                    Animation rotation = AnimationUtils.loadAnimation(this, R.anim.actionbar_rotate);
                    if (iv != null && rotation != null) {
                        iv.startAnimation(rotation);
                    }
                    MenuItemCompat.setActionView(refreshItem, iv);
                } else {
                    MenuItemCompat.getActionView(refreshItem).clearAnimation();
                    MenuItemCompat.setActionView(refreshItem, null);
                }

            }
        }
    }

anim.xml

<?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="500"
    android:repeatCount="-1"
    android:interpolator="@android:anim/linear_interpolator" />

加入的一层布局:

layout.xml

<?xml version="1.0" encoding="utf-8"?>

<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_action_refresh"
    style="@style/Widget.AppCompat.Light.ActionButton"
    />

由于兼容API7 ,所以用的 AppCompat

参考:http://stackoverflow.com/questions/9731602/animated-icon-for-actionitem

相关推荐