如何在Android中使按钮闪烁?

问题描述 投票:1回答:2

如果用户(在我的quizgame中)选择了错误答案,则具有正确答案的按钮应呈绿色闪烁。到目前为止我这样做了:

    if(answerTrue)
        for (int i = 0; i < 2000; i = i + 250) {
            handler.postDelayed(rbl_blinkNormal, i);
            i = i + 250;
            handler.postDelayed(rbl_blinkGreen, i);
        }

和可运行的:绿色:

 rbl_blinkGreen= new Runnable() {
     @Override
     public void run() {
         btn_richtig.setBackgroundResource(R.drawable.color_green_btn);
     }

 };

正常:

 rbl_blinkNormal= new Runnable() {
     @Override
     public void run() {
         btn_richtig.setBackgroundResource(R.drawable.color_black_btn);
     }

 };

它工作正常,但像这样我每250ms调用postDelayed()。这可能会影响我的应用程序性能,还有更好的方法吗?

android performance runnable
2个回答
5
投票

将颜色设置为绿色后,可以为按钮设置动画。我的意思是,

if(answerTrue){

    // Set the color of the button to GREEN once.

    // Next, animate its visibility with the set color - which is GREEN as follows:

    Animation anim = new AlphaAnimation(0.0f, 1.0f);
    anim.setDuration(50); //You can manage the blinking time with this parameter
    anim.setStartOffset(20);
    anim.setRepeatMode(Animation.REVERSE);
    anim.setRepeatCount(Animation.INFINITE);
    button.startAnimation(anim);
}

同样,您可以设置其他按钮的动画并在您感觉时停止动画。

资料来源:Blinking Text in android view


0
投票

如果您只想使图像闪烁,这是一个例子。

Button bt_notes = (Button) findViewById(R.id.bt_notes);
int bt_notes_blink = 0;

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int DrawableImage[] = {R.drawable.picto_keys, R.drawable.picto_blank};
                Resources res = getApplicationContext().getResources();
                bt_notes.setCompoundDrawablesWithIntrinsicBounds(null, null, null, res.getDrawable(DrawableImage[bt_notes_blink]));
                bt_notes_blink++;
                if (bt_notes_blink == 2) { bt_notes_blink = 0; }
                handler.postDelayed(this, 500);
            }
        });
    }
}, 0);
© www.soinside.com 2019 - 2024. All rights reserved.