【问题标题】:Add animated icon to Android Action Bar (no Action Bar Sherlock)将动画图标添加到 Android 操作栏(无操作栏 Sherlock)
【发布时间】:2012-12-10 20:57:48
【问题描述】:

我找到了一些使用 ActionBar Sherlock (Stackoverflow Link) 将动画项目添加到操作栏的解决方案

是否有仅使用默认操作栏的示例?

我尝试了链接中给出的方法,它确实为按钮创建了动画。问题是在设置 actionVIew 后,按钮在操作栏中左对齐。

【问题讨论】:

  • 您是否尝试过从给定链接到默认 ActionBar 的解决方案?
  • 是的,我试过了。动画确实有效,但 ActionItem 的大小不起作用。我想我会扩展我的描述。

标签: android android-actionbar


【解决方案1】:

我必须为一个项目这样做。您只需将 ImageView 子类化并将该类用作菜单项的 Action View。

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

这是您从菜单 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>

【讨论】:

  • 你为什么在 hadler 中调用“initializeAnimation”?