I'm trying to get my refresh button on my Actionbar to rotate, but I'm having some trouble getting it to work. The View just seems to lose it's horziontal margin/padding (which I haven't set anywhere), and does not rotate. I get no null errors, crashes, or anything else that could point me in the right direction. What am I doing wrong? Any help would be much apreciated.
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"
/>
anim/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" />
Just change this line:
item.setActionView(R.layout.action_refresh);
To this:
MenuItemCompat.setActionView(item, imageView);
The reason it doesn't animate with the original line is because you are setting the action view to the static image resource, not the imageView that you set up to animate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With