Home » Android » Android : setActionView(null) doesn't remove view and width trouble on MenuItem with ActionView

Android : setActionView(null) doesn't remove view and width trouble on MenuItem with ActionView

Posted by: admin June 15, 2020 Leave a comment

Questions:

I try to animate a MenuItem for ActionBar with an action view in a way simular to ActionBarHelper for Honeycomb to have a rotative refresh button. But I have 2 troubles :

  1. When I display action view, width of item is smaller than MenuItem (see part 1 and 2 of screenshot)
  2. When I want to stop animation and return to default MenuItem state via setActionView(null), my action view is still displayed inside my MenuItem (part 3 of screenshot)

Different steps of MenuItem (Screenshots)

ActionView Layout (R.layout.menu_item_refresh) is :

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

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_menu_refresh" />

</LinearLayout>

onOptionsItemSelected methods code is :

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()){               
        default:
            return super.onOptionsItemSelected(item);

        case R.id.Menu_Feed_Refresh:
            mAnimatedItem = item;
            item.setActionView(R.layout.menu_item_refresh);
            item.startAnimation(mAnimation);

            load();
            return true;
    }
}

When load finished, I call an handler mAnimatedItem.setActionView(null)

How to&Answers:

if i undestood your code right, you apply animation to MenuItem. you delete ActionView by setActionView(null), but menuItem animates.

you need to get image from ActionView and apply animation to it:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){               
    default:
        return super.onOptionsItemSelected(item);

    case R.id.Menu_Feed_Refresh:
        mAnimatedItem = item;
        item.setActionView(R.layout.menu_item_refresh);
        ImageView iv = (ImageView) item.getActionView().findViewById(R.id.refresh_image_id);
        iv.startAnimation(mAnimation);
        load();
        return true;
    }
}

Answer:

Call mAnimation.clearAnimation() when you want to stop.