Android,如何使用动画设置按钮背景颜色?

4
我有一个按钮,当点击时,我希望该按钮似乎会通过在两个背景颜色之间来回切换而闪烁这个答案使用AlphaAnimation使按钮闪烁:
    final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
    animation.setDuration(500); // duration - half a second
    animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
    animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in
    final Button btn = (Button) findViewById(R.id.your_btn);
    btn.startAnimation(animation);

但我无法让它在背景色下正常工作。

Android Studio将自动完成以下内容:

animation = new Animation() {
    @Override
    public void setBackgroundColor(int bg) {
        super.setBackgroundColor(bg);
    }
};

我试图将它应用于按钮(使用bg = Color.parseColor("#ffff9434")),但不起作用。

提前谢谢。

编辑

我还尝试了以下方法,但已过时且无效(来自这里

    Button btn = (Button)this.findViewById(R.id.btn1);
    //Let's change background's color from blue to red.
    ColorDrawable[] color = {new ColorDrawable(Color.BLUE), new ColorDrawable(Color.RED)};
    TransitionDrawable trans = new TransitionDrawable(color);
    //This will work also on old devices. The latest API says you have to use setBackground instead.
    btn.setBackgroundDrawable(trans);
    trans.startTransition(5000);

ETID 2

已解决,见下方答案。


找到了一个解决方案,并发布了一个答案,但我会离开,这样其他人就有四个解决方案而不是三个。 - Birrel
好的先生,很好.. - Elltz
1个回答

6

搞定了!感谢这篇文章的帮助!

final AnimationDrawable drawable = new AnimationDrawable();
final Handler handler = new Handler();

drawable.addFrame(new ColorDrawable(Color.RED), 400);
drawable.addFrame(new ColorDrawable(Color.GREEN), 400);
drawable.setOneShot(false);

btn = (Button) view.findViewById(R.id.flashBtn);

btn.setBackgroundDrawable(drawable);
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        drawable.start();
    }
    }, 100);

运行得非常好!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接