简体   繁体   中英

Add animated icon to Android Action Bar (no Action Bar Sherlock)

I found some solutions for adding an animated item to a action bar using the ActionBar Sherlock ( Stackoverflow Link )

Are there any examples when just using the default Action Bar?

I tried the approach given in the link, it does create an animation for the button. THe problem is that the button is left aligned inside the action bar after the actionVIew is set.

I had to do that for a project. You just subclass ImageView and use that class as your Action View for the menu item.

package com.---.events.android;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView;

public class AnimatedImageView extends ImageView {

    public AnimatedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public AnimatedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AnimatedImageView(Context context) {
        super(context);
    }

    public void initializeAnimation(){
        setImageDrawable(null);
        setBackgroundAnimation();
        AnimationDrawable da = (AnimationDrawable) getBackground();
        da.start();
    }

    public void setBackgroundAnimation() {
        setBackgroundResource(R.drawable.logo_animation); // this is an animation-list
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        Handler handler = new Handler();
        final AnimatedImageView me = this; 
        handler.post(new Runnable(){
            public void run() {
                me.initializeAnimation();
            }
        });
    }
}

Here's how you specify the Action View from your menu XML.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_animation"
          android:title="test"
          android:showAsAction="always" 
          android:actionViewClass="com.--.events.android.AnimatedImageView" />
</menu>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM