0

I'm making an Android app and I have a refresh button in my toolbar, defined in a menu like this :

<item
android:id="@+id/action_refresh"
android:icon="@drawable/ic_baseline_refresh_24"
android:title=""
app:showAsAction="always" />

and I'd like to start the rotation of it when the activity is created

I succeed in rotating it when touching it :

val view = findViewById<View>(R.id.action_refresh)
ObjectAnimator.ofFloat(view, "rotation", 360f).apply {
    duration = 1000
    repeatCount = Animation.INFINITE
    interpolator = LinearInterpolator()
    doOnCancel {
        view?.rotation = 0f
    }
}.start()

in onOptionsItemSelected

So i'd like to do the same thing in onCreateMenu, but I can't. I tested dozen of solutions from StackOverflow and nothing helps

EDIT:

It works if I set an app:actionViewClass on the menu item but I don't know what class to choose, it is a button like this

Screen of the button

Kureteiyu
  • 529
  • 4
  • 10

2 Answers2

0

So i'd like to do the same thing in onCreateMenu, but I can't.

That's because onCreateOptionsMenu() is called after onCreate(), which means calling findViewById() directly inside onCreateOptionsMenu() will definitely throw NullPointerException, because the content root View hasn't been inflated/created yet.

You can do it in onCreate().

Sam Chen
  • 7,597
  • 2
  • 40
  • 73
  • Oh thanks! Then how? I tried findViewById(R.id.action_refresh), toolbar.findViewById(R.id.action_refresh), and saving the menu in a variable then menu?.findItem(R.id.action_refresh)?.actionView, and none of it do anything. – Kureteiyu Feb 07 '21 at 21:21
  • @TheDevKiller This may help: https://stackoverflow.com/questions/8614293/android-get-view-reference-to-a-menu-item – Sam Chen Feb 07 '21 at 22:29
  • I tried to set the actionViewClass but I don't know which class to put. I tried many like ImageView or ImageButton and it works, but for ImageView I can't succeed in putting the icon, no image appears, and for the ImageButton it's just an ugly grey rectangle. Any ideas? – Kureteiyu Feb 07 '21 at 22:49
0

I found a workaround finding the view by its ID from onCreate with a delay of 100ms, but if someone have a better solution I still take it

Kureteiyu
  • 529
  • 4
  • 10