ActionItem的动画图标

时间:2012-03-16 03:51:14

标签: android android-animation actionbarsherlock

我一直在寻找适合我问题的解决办法,但我似乎找不到一个。我有一个ActionBar(ActionBarSherlock),其菜单从XML文件中膨胀,该菜单包含一个项目,并且该项目显示为ActionItem。

菜单:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >    
    <item
        android:id="@+id/menu_refresh"       
        android:icon="@drawable/ic_menu_refresh"
        android:showAsAction="ifRoom"
        android:title="Refresh"/>    
</menu>

活性

[...]
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.mymenu, menu);
    return true;
  }
[...]

ActionItem显示时带有图标但没有文字但是当用户点击ActionItem时,我希望图标开始动画,更具体地说,就是在适当的位置旋转。有问题的图标是刷新图标。

我意识到ActionBar支持使用自定义视图(Adding an Action View)但是这个自定义视图已经扩展到覆盖ActionBar的整个区域并且实际上阻止了除应用程序图标之外的所有内容,在我的情况下它不是什么我在寻找。

所以我的下一次尝试是尝试使用AnimationDrawable并逐帧定义我的动画,将drawable设置为菜单项的图标,然后在onOptionsItemSelected(MenuItem item)中获取图标并使用{开始制作动画{1}}。但这并不成功。有谁知道有任何方法可以达到这个效果?

7 个答案:

答案 0 :(得分:172)

你走在正确的轨道上。以下是GitHub Gaug.es应用程序将如何实现它。

首先他们定义动画XML:

<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" />

现在为动作视图定义布局:

<ImageView 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.Sherlock.ActionButton" />

我们需要做的就是在点击项目时启用此视图:

 public void refresh() {
     /* Attach a rotating ImageView to the refresh item as an ActionView */
     LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     ImageView iv = (ImageView) inflater.inflate(R.layout.refresh_action_view, null);

     Animation rotation = AnimationUtils.loadAnimation(getActivity(), R.anim.clockwise_refresh);
     rotation.setRepeatCount(Animation.INFINITE);
     iv.startAnimation(rotation);

     refreshItem.setActionView(iv);

     //TODO trigger loading
 }

加载完成后,只需停止动画并清除视图:

public void completeRefresh() {
    refreshItem.getActionView().clearAnimation();
    refreshItem.setActionView(null);
}

你已经完成了!

还有一些事情要做:

  • 缓存动作视图布局通胀和动画通胀。它们很慢,所以你只想做一次。
  • null
  • 中添加completeRefresh()项支票

以下是该应用的拉取请求:https://github.com/github/gauges-android/pull/13/files

答案 1 :(得分:16)

我使用ActionBarSherlock解决了一些问题,我想出了这个:

<强> RES /布局/ indeterminate_progress_action.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="48dp"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:paddingRight="12dp" >

    <ProgressBar
        style="@style/Widget.Sherlock.ProgressBar"
        android:layout_width="44dp"
        android:layout_height="32dp"
        android:layout_gravity="left"
        android:layout_marginLeft="12dp"
        android:indeterminate="true"
        android:indeterminateDrawable="@drawable/rotation_refresh"
        android:paddingRight="12dp" />

</FrameLayout>

<强> RES /布局-V11 / indeterminate_progress_action.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center" >

    <ProgressBar
        style="@style/Widget.Sherlock.ProgressBar"
        android:layout_width="32dp"
        android:layout_gravity="left"
        android:layout_marginRight="12dp"
        android:layout_marginLeft="12dp"
        android:layout_height="32dp"
        android:indeterminateDrawable="@drawable/rotation_refresh"
        android:indeterminate="true" />

</FrameLayout>

<强> RES /抽拉/ rotation_refresh.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%"
    android:pivotY="50%"
    android:drawable="@drawable/ic_menu_navigation_refresh"
    android:repeatCount="infinite" >

</rotate>

活动中的代码(我在ActivityWithRefresh父类中有它)

// Helper methods
protected MenuItem refreshItem = null;  

protected void setRefreshItem(MenuItem item) {
    refreshItem = item;
}

protected void stopRefresh() {
    if (refreshItem != null) {
        refreshItem.setActionView(null);
    }
}

protected void runRefresh() {
    if (refreshItem != null) {
        refreshItem.setActionView(R.layout.indeterminate_progress_action);
    }
}
活动创建菜单项

private static final int MENU_REFRESH = 1;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, "Refresh data")
            .setIcon(R.drawable.ic_menu_navigation_refresh)
            .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
    setRefreshItem(menu.findItem(MENU_REFRESH));
    refreshData();
    return super.onCreateOptionsMenu(menu);
}

private void refreshData(){
    runRefresh();
    // work with your data
    // for animation to work properly, make AsyncTask to refresh your data
    // or delegate work anyhow to another thread
    // If you'll have work at UI thread, animation might not work at all
    stopRefresh();
}

图标,这是drawable-xhdpi/ic_menu_navigation_refresh.png
drawable-xhdpi/ic_menu_navigation_refresh.png

可以在http://developer.android.com/design/downloads/index.html#action-bar-icon-pack

中找到

答案 2 :(得分:6)

除了杰克沃顿所说的,你应该做以下工作以确保动画在加载完成后能够顺利停止并且不会跳转

首先,创建一个新的布尔值(对于整个类):

private boolean isCurrentlyLoading;

找到开始加载的方法。在活动开始加载时将布尔值设置为true。

isCurrentlyLoading = true;

找到加载完成时启动的方法。而不是清除动画,将布尔值设置为false。

isCurrentlyLoading = false;

在动画上设置AnimationListener:

animationRotate.setAnimationListener(new AnimationListener() {

然后,每次动画执行一次,这意味着当你的图标旋转一次,检查加载状态,如果不再加载,动画将停止。

@Override
public void onAnimationRepeat(Animation animation) {
    if(!isCurrentlyLoading) {
        refreshItem.getActionView().clearAnimation();
        refreshItem.setActionView(null);
    }
}

这样,动画只有在它已经旋转到结束时才能停止,并且很快就会重复动画并且不再加载动画。

这至少是我想要实现Jake的想法时所做的。

答案 3 :(得分:1)

还可以选择在代码中创建旋转。全部剪辑:

    MenuItem item = getToolbar().getMenu().findItem(Menu.FIRST);
    if (item == null) return;

    // define the animation for rotation
    Animation animation = new RotateAnimation(0.0f, 360.0f,
            Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f);
    animation.setDuration(1000);
    //animRotate = AnimationUtils.loadAnimation(this, R.anim.rotation);

    animation.setRepeatCount(Animation.INFINITE);

    ImageView imageView = new ImageView(this);
    imageView.setImageDrawable(UIHelper.getIcon(this, MMEXIconFont.Icon.mmx_refresh));

    imageView.startAnimation(animation);
    item.setActionView(imageView);

答案 4 :(得分:0)

使用支持库,我们可以在没有自定义actionView的情况下设置动画图标。

private AnimationDrawableWrapper drawableWrapper;    

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //inflate menu...

    MenuItem menuItem = menu.findItem(R.id.your_icon);
    Drawable icon = menuItem.getIcon();
    drawableWrapper = new AnimationDrawableWrapper(getResources(), icon);
    menuItem.setIcon(drawableWrapper);
    return true;
}

public void startRotateIconAnimation() {
    ValueAnimator animator = ObjectAnimator.ofInt(0, 360);
    animator.addUpdateListener(animation -> {
        int rotation = (int) animation.getAnimatedValue();
        drawableWrapper.setRotation(rotation);
    });
    animator.start();
}

我们无法直接为drawable制作动画,因此请使用DrawableWrapper(来自android.support.v7 for API&lt; 21):

public class AnimationDrawableWrapper extends DrawableWrapper {

    private float rotation;
    private Rect bounds;

    public AnimationDrawableWrapper(Resources resources, Drawable drawable) {
        super(vectorToBitmapDrawableIfNeeded(resources, drawable));
        bounds = new Rect();
    }

    @Override
    public void draw(Canvas canvas) {
        copyBounds(bounds);
        canvas.save();
        canvas.rotate(rotation, bounds.centerX(), bounds.centerY());
        super.draw(canvas);
        canvas.restore();
    }

    public void setRotation(float degrees) {
        this.rotation = degrees % 360;
        invalidateSelf();
    }

    /**
     * Workaround for issues related to vector drawables rotation and scaling:
     * https://code.google.com/p/android/issues/detail?id=192413
     * https://code.google.com/p/android/issues/detail?id=208453
     */
    private static Drawable vectorToBitmapDrawableIfNeeded(Resources resources, Drawable drawable) {
        if (drawable instanceof VectorDrawable) {
            Bitmap b = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(b);
            drawable.setBounds(0, 0, c.getWidth(), c.getHeight());
            drawable.draw(c);
            drawable = new BitmapDrawable(resources, b);
        }
        return drawable;
    }
}

我从这里接受了DrawableWrapper的想法:https://stackoverflow.com/a/39108111/5541688

答案 5 :(得分:0)

它是我非常简单的解决方案(例如,需要一些重构) 与标准菜单项一起使用, 您可以在任意数量的状态,图标,动画,逻辑等中使用它。

在“活动”类别中:

import sys
try:
    import Tkinter as Tk
except:
    import tkinter as Tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from numpy.random import rand
from matplotlib.widgets import RectangleSelector

root = Tk.Tk()
root_panel = Tk.Frame(root)
root_panel.pack(side="top", fill="both", expand="no")

fig = Figure()
ax = fig.add_subplot(111)
img = ax.imshow(rand(10, 5), extent=(1, 2, 1, 2), picker=True)
ax.axis([0, 3, 0, 3])

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def onselect(eclick, erelease):
    x1, y1 = eclick.xdata, eclick.ydata
    x2, y2 = erelease.xdata, erelease.ydata
    try:
        cropped = img[y1:y2, x1:x2] # this raises TypeError: 'AxesImage' object is not subscriptable
        ax.clear()
        ax.imshow(cropped)
        fig.canvas.draw()
    except Exception as e:
        print('Error:', e)

# must set default value of event argument,
# otherwise problem when triggered by ROIBtn
def toggle_selector(event=None):
    #print('toggle_selector:', event.key if event else switch_variable.get())
    active = None
    if event:
        # triggered by keypressed
        if event.key in 'Qq':
            if selector.active: active = 0
        elif event.key in 'Aa':
            if not selector.active: active = 1
    else:
        # triggered by ROIBtn
        active = switch_variable.get()
    if active is not None:
        switch_variable.set(active) # update ROIBtn
        selector.set_active(active == 1)
        print('RectangleSelector {}activated.'.format('' if active == 1 else 'de'))

# ROI BUTTON
switch_variable = Tk.IntVar()
# set command option to toggle_selector()
ROIBtn = Tk.Checkbutton(master=root_panel, text='ROI', indicatoron=False, variable=switch_variable, command=toggle_selector)
ROIBtn.pack(side=Tk.LEFT)

selector = RectangleSelector(ax, onselect, drawtype='box')
selector.set_active(switch_variable.get())
fig.canvas.mpl_connect('key_press_event', toggle_selector)

root.mainloop()

标准监听器:

private enum RefreshMode {update, actual, outdated} 

进入refreshData()就像这样:

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_refresh: {
            refreshData(null);
            break;
        }
    }
}

用于定义图标颜色或动画的方法:

setRefreshIcon(RefreshMode.update);
// update your data
setRefreshIcon(RefreshMode.actual);

有2个带有图标的布局(R.layout.refresh_action_view(+“ _actual”)):

 void setRefreshIcon(RefreshMode refreshMode) {

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Animation rotation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotation);
    FrameLayout iconView;

    switch (refreshMode) {
        case update: {
            iconView = (FrameLayout) inflater.inflate(R.layout.refresh_action_view,null);
            iconView.startAnimation(rotation);
            toolbar.getMenu().findItem(R.id.menu_refresh).setActionView(iconView);
            break;
        }
        case actual: {
            toolbar.getMenu().findItem(R.id.menu_refresh).getActionView().clearAnimation();
            iconView = (FrameLayout) inflater.inflate(R.layout.refresh_action_view_actual,null);
            toolbar.getMenu().findItem(R.id.menu_refresh).setActionView(null);
            toolbar.getMenu().findItem(R.id.menu_refresh).setIcon(R.drawable.ic_refresh_24dp_actual);
            break;
        }
        case outdated:{
            toolbar.getMenu().findItem(R.id.menu_refresh).setIcon(R.drawable.ic_refresh_24dp);
            break;
        }
        default: {
        }
    }
}

在这种情况下(standby)旋转动画(R.anim.rotation):

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:gravity="center">
<ImageView
    android:src="@drawable/ic_refresh_24dp_actual" // or ="@drawable/ic_refresh_24dp"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_margin="12dp"/>
</FrameLayout>

答案 6 :(得分:0)

最好的方法在这里:

public class HomeActivity extends AppCompatActivity {
    public static ActionMenuItemView btsync;
    public static RotateAnimation rotateAnimation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    rotateAnimation = new RotateAnimation(360, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    rotateAnimation.setDuration((long) 2*500);
    rotateAnimation.setRepeatCount(Animation.INFINITE);

然后:

private void sync() {
    btsync = this.findViewById(R.id.action_sync); //remember that u cant access this view at onCreate() or onStart() or onResume() or onPostResume() or onPostCreate() or onCreateOptionsMenu() or onPrepareOptionsMenu()
    if (isSyncServiceRunning(HomeActivity.this)) {
        showConfirmStopDialog();
    } else {
        if (btsync != null) {
            btsync.startAnimation(rotateAnimation);
        }
        Context context = getApplicationContext();
        context.startService(new Intent(context, SyncService.class));
    }
}

记住,您无法访问“ btsync = this.findViewById(R.id.action_sync);”在onCreate()或onStart()或onResume()或onPostResume()或onPostCreate()或onCreateOptionsMenu()或onPrepareOptionsMenu() 如果您想在活动开始后立即获取它,则将其放后延迟:

public static void refreshSync(Activity context) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(new Runnable() {
        public void run() {
            btsync = context.findViewById(R.id.action_sync);
            if (btsync != null && isSyncServiceRunning(context)) {
                btsync.startAnimation(rotateAnimation);
            } else if (btsync != null) {
                btsync.clearAnimation();
            }
        }
    }, 1000);
}