How to make a Button blink in Android?

本小妞迷上赌 提交于 2019-12-11 07:19:02

问题


If the user (in my quizgame) chooses the false answer, the button with the correct answer should blink green. So far i did it like this:

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

And the runnables: Green:

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

 };

Normal:

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

 };

It works fine but like this Im calling the postDelayed() every 250ms. May this impact my application performance and is there any better way to do this?


回答1:


You can animate your button once you set its color to say GREEN. I mean,

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

Similarly, you can animate the other button and stop animation when you feel like.

Source: Blinking Text in android view




回答2:


If you want to blink the image only, here is an example.

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


来源:https://stackoverflow.com/questions/43705249/how-to-make-a-button-blink-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!