0

I need help with an refresh button in my action bar. I already have this button but I want to let it rotate onclick. I've wrote this code here but I'm getting an error and the app is crashing:

The error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Mx XML:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:compat="http://schemas.android.com/tools">

    <item
        android:id="@+id/menu_reloadbutton"
        android:icon="@drawable/ic_menu_reloadentry"
        android:title="@string/menu_reloadentry"
        app:showAsAction="ifRoom"/>

</menu>

My code:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        inflater.inflate(R.menu.menu_training, menu);

        // Declare ImageView and Animation for rotation animation
        MenuItem reloadButton = (MenuItem) menu.findItem(R.id.menu_reloadbutton);
        final Animation rotation = AnimationUtils.loadAnimation(getActivity(), R.anim.animation_rotate);

        if (reloadButton != null) {
            //reloadButton.setImageResource(R.drawable.ic_menu_reloadentry);
            reloadButton.getActionView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    rotation.setRepeatCount(Animation.INFINITE);
                    view.startAnimation(rotation);
                }
            });
        }
    }
ItsOdi1
  • 219
  • 3
  • 22
  • 1
    Here is the canonical, but it's old: http://stackoverflow.com/questions/9731602/animated-icon-for-actionitem Here is a more current answer as well: http://stackoverflow.com/a/19225651/4409409 – Daniel Nugent Jan 30 '17 at 17:17
  • @DanielNugent Okay thanks! I've searched a lot but I never saw this answer... Please can you remove this duplicate? Because I'm blocked asking questions.. I will delete this question after this. – ItsOdi1 Jan 30 '17 at 17:18
  • 1
    @DanielNugent Thanks a lot :) – ItsOdi1 Jan 30 '17 at 17:20
  • 1
    Possible duplicate of [Animated menu item "jumps" when animation starts](http://stackoverflow.com/questions/19139775/animated-menu-item-jumps-when-animation-starts) – Rod_Algonquin Jan 30 '17 at 17:20
  • @DanielNugent Can you take a look at this? – ItsOdi1 Jan 30 '17 at 19:43

1 Answers1

1

You need setActionView(R.layout.imageview_reload) before reloadButton.getActionView()

Just add layout file res/layout/imageview_reload

<?xml version="1.0" encoding="utf-8"?>
<ImageView 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 style="@android:style/Widget.ActionButton" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content"
 android:src="@drawable/ic_menu_reloadentry" />
McCoy AI
  • 11
  • 2