我有一个函数,如果接受为true,则启动线程以闪烁视图,但如果收到错误,如何停止它?
private void blinkText(boolean b){
final Handler handler = new Handler();
if(b)
{
new Thread(new Runnable() {
@Override
public void run() {
int timeToBlink = 1000; //in ms
try{
Thread.sleep(timeToBlink);
}catch (Exception e) {
}
handler.post(new Runnable() {
@Override
public void run() {
TextView txt = (TextView) findViewById(R.id.tv);
if(txt.getVisibility() == View.VISIBLE){
txt.setVisibility(View.INVISIBLE);
}else{
txt.setVisibility(View.VISIBLE);
}
blinkText(true);
}
});
}}).start();
}
else
{
// stop blinking
}
}
答案 0 :(得分:2)
您可以在xml中定义闪烁动画,并在初始化后将其添加到textview中:
<强> RES /动画/ blink.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="200"
android:repeatMode="reverse"
android:repeatCount="infinite"
xmlns:android="http://schemas.android.com/apk/res/android">
</alpha>
添加动画进行观看:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button);
TextView textView = (TextView) this.findViewById(R.id.textview);
Animation blink = AnimationUtils.loadAnimation(this, R.anim.blink);
textView.setAnimation(blink);
}
开始:
textView.getAnimation().start()
停止:
textView.getAnimation().cancel()
textView.getAnimation().reset()
答案 1 :(得分:0)
您需要创建一个布尔字段作为类成员(boolean mStopBlink = false;)并跟踪TextView当前是否闪烁:
txt.setVisibility(View.VISIBLE);
if(!mStopBlink){
txt.setVisibility(View.INVISIBLE);