Refresh menu item animation in ActionBarSherlock

前端 未结 2 1835
南方客
南方客 2020-12-19 02:18
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case android.R.id.home:
        return true;

    case R.id.searchIcon:
           


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-19 02:52

    The issue is that you're not handling all menu inflation in onCreateOptionsMenu(). The basic logic for an ActionBar refresh animation I've seen used in apps with open source , for example Andlytics (and also used myself in projects), is to implement a boolean flag in onCreateOptionsMenu() to decide whether to show the refresh animation.

    You can implement it like this: When your refresh() method is called, it sets the boolean isRefreshing flag to true and calls inValidateOptionsMenu() which 'behind the scene' calls onCreateOptionsMenu() to start the animation:

    Inflate the menu in onCreateOptionsMenu(...):

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        super.onCreateOptionsMenu(menu, inflater);
        //inflate a menu which shows the non-animated refresh icon
        inflater.inflate(R.menu.my_ab_menu, menu);
    
        if (isRefreshing) {
            //if we're refreshing, show the animation
            MenuItem item = menu.findItem(R.id.refreshMenuItem);
            item.setActionView(R.layout.action_bar_indeterminate_progress);
            ImageView iv = (ImageView) item.getActionView().findViewById(R.id.loadingImageView);
            ((AnimationDrawable) iv.getDrawable()).start();
        }
    }
    

    Start animation like so:

     public void refresh(){
            isRefreshing = true;
            inValidateOptionsMenu();
        }
    

    If you want the user to start the animation when he taps the refresh icon, do like this in onOptionsItemSelected():

    case R.id.refreshMenuItem:
        isRefreshing = true;
        item.setActionView(R.layout.action_bar_indeterminate_progress);
        ImageView iv = (ImageView) item.getActionView().findViewById(R.id.loadingImageView);
        ((AnimationDrawable) iv.getDrawable()).start();
        //...
    

    To stop the animation call:

    isRefreshing = false;
    invalidateOptionsMenu();
    

    This code is from a Fragment so you may have to tweak if for an Activity, but I think it communicates the basic idea.

提交回复
热议问题