2014-01-06 119 views
1

如果接受true,我有啓動閃爍視圖線程的函數,但如果接收到false,我該如何停止它?停止視圖閃爍線程

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 
    } 

}

+1

爲什麼不使用Android動畫呢? –

回答

2

可以定義在xml中閃爍動畫並在初始化後將其添加到您的textview中:

res/anim/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() 
0

你需要創建一個布爾字段作爲類成員(布爾mStopBlink = FALSE)和軌道的TextView是否正在閃爍:

txt.setVisibility(View.VISIBLE); 
if(!mStopBlink){ 
    txt.setVisibility(View.INVISIBLE);