Unable to get Actionbar icon for animation

I am trying to rotate my update button on my Actionbar, but I am having problems with its operation. The view simply seems to lose its horziontal margin / padding (which I did not set anywhere) and does not rotate. I am not getting any zero errors, crashes or anything else that might point me in the right direction. What am I doing wrong? Any help would be greatly appreciated.

Main.java:

public class Main extends ActionBarActivity{

...

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_refresh:
                refresh();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    public void refresh() {

        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ImageView imageView = (ImageView) inflater.inflate(R.layout.action_refresh, null);

        Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate);
        rotation.setRepeatCount(Animation.INFINITE);
        imageView.startAnimation(rotation);

        MenuItem item = menu.findItem(R.id.action_refresh);
        item.setActionView(R.layout.action_refresh);

   }
}

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:yourapp="http://schemas.android.com/apk/res-auto" >

    <item android:id="@+id/action_refresh"
          android:icon="@drawable/ic_action_refresh"
          android:title="refresh"
          android:actionLayout="@layout/action_refresh"
          yourapp:showAsAction="ifRoom"
          />

    <item
          android:id="@+id/category_spinner_item"
          android:showAsAction="ifRoom"
          android:actionLayout="@layout/action_sort"
          />
</menu>

action_refresh.xml

<?xml version="1.0" encoding="utf-8"?>

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/ic_action_refresh"
           />

anit / rotate.xml

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="10000"
        android:interpolator="@android:anim/linear_interpolator" />
+4
source share
1 answer

Just change this line:

item.setActionView(R.layout.action_refresh);

For this:

MenuItemCompat.setActionView(item, imageView);

, , , , , .

+2

Source: https://habr.com/ru/post/1536038/


All Articles