首页 > 代码库 > 如何给Actionbar添加动画(支持2.3)

如何给Actionbar添加动画(支持2.3)

注:需要导入v4包

private MenuItem refreshItem;

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_refresh:        
            showRefreshAnimation(item);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

 

 

    private void showRefreshAnimation(MenuItem item) {
        refreshItem = item;
 
        //这里使用一个ImageView设置成MenuItem的ActionView,这样我们就可以使用这个ImageView显示旋转动画了
        ImageView refreshActionView = (ImageView) LayoutInflater.from(getActivity()).
          inflate(R.layout.actionbar_refresh_view, null);
        refreshActionView.setImageResource(R.drawable.refreshnormal);
//        refreshItem.setActionView(refreshActionView);  //该方法必须11以上
        MenuItemCompat.setActionView(item, refreshActionView);//替换为使用v4兼容包
        //显示刷新动画
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.rotateanim);
        animation.setRepeatMode(Animation.RESTART);
        animation.setRepeatCount(Animation.INFINITE);
        refreshActionView.startAnimation(animation);
    }

  public void hideRefreshAnimation() {
        if (refreshItem != null) {
        
           /// View view = refreshItem.getActionView();

View view = MenuItemCompat.getActionView(refreshItem);
            if (view != null) {
                view.clearAnimation();
                refreshItem.setActionView(null);
            }
        }
    }

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:funshion="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/action_deleted"
        android:icon="@drawable/common_delete_btn_selector"
        android:title="@string/delete"
        funshion:showAsAction="ifRoom"/>
    <item
        android:id="@+id/action_refresh"
        android:icon="@drawable/refreshnormal"
        android:title="@string/refresh"
        funshion:showAsAction="ifRoom"/>

</menu>


actionbar_refresh_view.xml

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    style="@android:style/Widget.ActionButton"
    android:layout_height="wrap_content"
    android:scaleType="centerInside" />

如何给Actionbar添加动画(支持2.3)