Animated menu item “jumps” when animation starts

偶尔善良 提交于 2019-11-29 10:56:29

I found the solution by setting the View also for the non-animated item to be the same. In the menu.xml:

<item
    android:id="@+id/action_refresh"
    android:orderInCategory="100"
    android:icon="@drawable/ic_menu_refresh"
    android:actionLayout="@layout/refresh_action_view"
    android:showAsAction="ifRoom"
    style="@android:style/Widget.ActionButton"
    android:title="@string/action_refresh"/>

Then, in onCreateOptionsMenu, I fetch the view in a member variable, and attach an onclick handler:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.orders, menu);
    final Menu m = menu;
    refreshItem = menu.findItem(R.id.action_refresh);
    refreshItem.getActionView().setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {   
                        m.performIdentifierAction(refreshItem.getItemId(), 0);
                    }
            });
    return true;
}

In onCreate, we load the animation:

    rotation = AnimationUtils.loadAnimation(this, R.anim.clockwise_refresh);
    rotation.setRepeatCount(Animation.INFINITE);

Finally, call this to start the animation:

refreshItem.getActionView().startAnimation(rotation);

and this to stop it:

refreshItem.getActionView().clearAnimation();

It's better to change the ImageView to an ImageButton, and not to change the layout on the menu item in menu.xml, then the image will not jump, and you also don't need to add the click handler. It will also be the correct size, which will not be the case if you use an ImageView instead of an ImageButton.

This is all you need:

<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/action_refresh"
android:src="@drawable/ic_menu_refresh"
android:id="@+id/refresh_view"
style="@android:style/Widget.ActionButton" />

Put some padding in ImageView. In my case, 8dp on each side.

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingRight="8dp"
    android:paddingLeft="8dp"
    android:src="@drawable/ic_action_important" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!