2013-10-22 92 views
0

我希望我的應用程序在更改按鈕文本之前等待片刻。我嘗試了不同的東西(wait(),Thread.sleep),但由於我希望等待時間是可變的,我決定使用CountDownTimer。請參見下面的代碼:Java Android CountDownTimer故障

public void onClick(View buttonClicked) { 
    if (i == 0) { 
     button.setText("Wait"); 
     waitingTime = (long) (Math.random() * 1000 + 10000); 
     new countdown(waitingTime, 1000); 
     time1 = System.currentTimeMillis(); 
     button.setText("Press"); 
     i++; 

出於某種原因,這doesn't工作,程序不等待。誰能幫幫我嗎?我沒有用CountDownTimer填充任何東西,因爲我認爲它應該只等幾秒鐘。

回答

0

螺紋也是可變的:

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

嘗試這個代碼

@Override 
public void onClick(View view) { 
if(i==0) { 
     YourActivity.this.runOnUiThread(new Runnable() { 



@Override    

public void run() { 
txtView.setText("please wait..."); 
} 
}); 

while(counter < 1000) { 
try { 
    Thread.sleep(100); 
}catch(InterruptedException e) { 
    e.printStackTrace(); 
} 
counter +=100; 
} 

txtView.setText("press"); 


i++; 


} 

} 

根據烏爾需要增加線程定時。如果需要編寫代碼的功能,你在哪裏傳遞睡眠值

編輯

mHandler =新的處理程序(); btn.setOnClickListener(新OnClickListener(){

 @Override 
     public void onClick(View view) { 
      btn.setText("wait"); 
      mHandler.postDelayed(new Runnable() { 

       @Override 
       public void run() { 
        btn.setText("press"); 
       } 
      }, 1500); 
     } 
    }); 
+0

我用的Thread.sleep,它並等待而不是按鈕isn't文本改變了......我怎樣才能正確顯示我的代碼? > \t公共無效的onClick(查看buttonClicked){ \t \t button.setText( 「等待」); \t \t如果(I == 0){ \t \t \t waitingTime =(長)(的Math.random()* 1000 + 3000); \t \t \t try { \t \t \t \t Thread.sleep(waitingTime); \t \t \t \t}趕上(例外五){ \t \t \t \t} \t \t \t TIME1 = System.currentTimeMillis的(); \t \t \t button.setText(「Press」); \t \t \t i ++; – Rob

+0

YourActivity.this.runOnUiThread(新的Runnable(){ \t \t \t \t \t \t \t \t \t \t @覆蓋 \t \t \t \t \t公共無效的run(){ \t \t \t \t \t \t按鈕。的setText( 「等待」); \t \t \t \t \t} \t \t \t \t});試試這個,而不是隻是button.setText(「等待」); –

+0

看看[這個](http://stackoverflow.com/questions/2300169/how-to-change-text-in-android-textview?answertab=votes#tab-top) –