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); } }); } }

5
  • 1
    Here is the canonical, but it's old: stackoverflow.com/questions/9731602/… Here is a more current answer as well: stackoverflow.com/a/19225651/4409409 Commented Jan 30, 2017 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. Commented Jan 30, 2017 at 17:18
  • 1
    @DanielNugent Thanks a lot :) Commented Jan 30, 2017 at 17:20
  • 1
    Possible duplicate of Animated menu item "jumps" when animation starts Commented Jan 30, 2017 at 17:20
  • @DanielNugent Can you take a look at this? Commented Jan 30, 2017 at 19:43

1 Answer 1

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" /> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.