按钮闪烁在Android中不起作用

时间:2013-07-25 13:11:05

标签: android android-button

以下用于闪烁按钮的代码:

public void blink() {
    new Thread(new Runnable() {
        public void run() {
            while (true) {
                int timeToBlink = 500;

                try { Thread.sleep(timeToBlink); } 
                catch (Exception e) {}

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        if (btn.getVisibility() == View.VISIBLE) {
                            btn.setVisibility(View.INVISIBLE);
                        } else {
                            btn.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        }
    }).start();
}

4 个答案:

答案 0 :(得分:2)

如何使用alpha动画?

以下代码段将为您提供帮助。

fade.xml(将其保存在res / anim / fade.xml下)

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fromAlpha="0.0"
    android:repeatCount="infinite"
    android:repeatMode="reverse"
    android:toAlpha="1.0" />

<强> MainActivity.java

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn= (Button) findViewById(R.id.btn);
        Animation myFadeInAnimation = AnimationUtils.loadAnimation(MainActivity.this,
                R.anim.fade);
        btn.startAnimation(myFadeInAnimation);

    }

}

答案 1 :(得分:0)

CountDownTimer怎么样?

final CountDownTimer blinkTimer = new CountDownTimer(120000 , 1000) { 
public void onTick(long millisUntilFinished) {
    if (btn.getVisibility() == View.VISIBLE) {
        btn.setVisibility(View.INVISIBLE);
    } else {
        btn.setVisibility(View.VISIBLE);
    } 
}

public void onFinish() {
    blinkTimer.start(); 
}
};

答案 2 :(得分:0)

可能是您在应用中处于无限循环中,因此runOnUIThread的runnable永远不会被执行。尝试使用alpha动画

答案 3 :(得分:0)

您可以使用:

Button button = (Button) findViewById(R.id.button1);

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