How to animate toolbar overflow menu icon

2020-07-16 09:00发布

问题:

Is there a way to animate the default 3-vertical-dotted menu icon on toolbar?

I use toolbar as actionbar with the standard code:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

and I also use the onCreateOptionsMenu method inside activity where I inflate my menu.xml file but I don't know how to gain more control over the overflow icon which is created automatically. What I'm most interested in is how to reference the menu icon So I can animate it. I don't care about the animation type. It can be a simple rotation animation

回答1:

Well, you play with the View specifically ActionMenuView so try this, copy the codes into your Activity

//we declare our objects globally
Toolbar tool;  ActionMenuView amv;

then override onPrepareOptionsMenu, what you decide to return is your choice

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    //to be safe you can check if children are greater than 1
    amv = (ActionMenuView) tool.getChildAt(1);//hope you've met amv
    return true;
}

now this is the crucial part- whenever you want to animate the "3 verticall dots" -(your overflow) you have to check visible children-(i.e if you want to) actually forget that

amv.getChildAt(amv.getChildCount()-1).startAnimation(AnimationUtils.loadAnimation(
        MainActivity.this,R.anim.abc_fade_in));

that gives you a basic fade-in animation- you can pimp your ride now.

EDIT 1:

The above code made assumptions that you have nothing added to your Toolbar aside from just inflating the menu in onCreateOptionsMenu.

Suppose you have a complex ToolBar use this rather for your initialisation

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    for(int i =0; i < tool.getChildCount(); ++i){
        if(tool.getChildAt(i).getClass().getSimpleName().equals("ActionMenuView")){
            amv = (ActionMenuView) tool.getChildAt(i);
            break;
        }
    }
    return true;
}

Also where you call your initialisation of amv View can be in either onCreateOptionsMenu or onPrepareOptionsMenu, i chose onPrepareOptionsMenu because i wanted readability

Hope it helps