2014-03-24 53 views
0

我設置了一個textview,我用它作爲定時器功能。 當計時器達到我想要的時間時,它應該開始一個新的活動,將我的佈局設置爲另一個。通過開始一個新的活動,它開始一次又一次

textfield=(TextView)findViewById(R.id.TVTimer); 
    handler = new Handler(); 
    Runnable runnable = new Runnable() { 

     @Override 
     public void run() { 
      while (Running){ 
       try { 

        Thread.sleep(1000); 
        } 

       catch (InterruptedException e) { 
        e.printStackTrace(); 
        // TODO: handle exception 
       } 
       handler.post(new Runnable() { 
        @Override 
        public void run(){ 
         number+=1; 
         textfield.setText(String.valueOf(number)); 
         if (number>5) { 
          Intent intent = new Intent(getApplicationContext(), Uebung2.class); 
          startActivity(intent); 

         } 

        } 
       }); 
      } 

     } 
    }; 
    new Thread(runnable).start(); 

這就是所謂類:

public class Uebung2 extends Oberklasse { 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    //Liegestützen1(2); 
    setContentView(R.layout.new); 

} 

}

現在我有問題後計時器達到的時間,我想,我的應用程序重新設置搜索佈局並再次每秒。 將佈局設置爲一次的解決方案是什麼?

回答

0

使用本

textfield=(TextView)findViewById(R.id.TVTimer); 
boolean loop = true; 

handler = new Handler(); 
Runnable runnable = new Runnable() { 

    @Override 
    public void run() { 
     while (loop){ 
      try { 

       Thread.sleep(1000); 
       } 

      catch (InterruptedException e) { 
       e.printStackTrace(); 
       // TODO: handle exception 
      } 
      handler.post(new Runnable() { 
       @Override 
       public void run(){ 
        number+=1; 
        textfield.setText(String.valueOf(number)); 
        if (number>5) { 
         loop = false; // this will end loop 
         Intent intent = new Intent(getApplicationContext(), Uebung2.class); 
         startActivity(intent); 

        } 

       } 
      }); 
     } 

    } 
}; 
new Thread(runnable).start(); 
+0

謝謝,有時你看不到最簡單的answear!非常感謝! – basti12354

2

怎麼一回事,因爲你有這個地方

handler.post(new Runnable() { 
       @Override 
       public void run(){ 
        number+=1; 
        textfield.setText(String.valueOf(number)); 
        if (number>5) { 
         Intent intent = new Intent(getApplicationContext(), Uebung2.class); 
         startActivity(intent); 

        } 

       } 
      }); 

while循環中。

也檢查您的「數量」值。

試試你的while循環

int i=1000; 
while (i<5000){ 
      try { 

       Thread.sleep(i); 
       i+=1000; 
       } 

      catch (InterruptedException e) { 
       e.printStackTrace(); 
       // TODO: handle exception 
      } 
     } 

並在此之後執行的可運行。

+0

我怎樣才能改變呢?有沒有可能? – basti12354

+0

@ user3433232你可以使用處理程序和gt刪除線程http://stackoverflow.com/questions/17839419/android-thread-for-a-timer – Raghunandan

+0

關閉,但每增加一次,我會增加睡眠時間。我不認爲這是OP想要的 – codeMagic

相關問題