2012-12-29 57 views
-1

我正在學習android,並且遇到了一個小問題。 我有一個按鈕,我想要移動到屏幕右側後,我點擊它。 我添加了一個按鈕被點擊後啓動的計時器,但當我點擊按鈕時程序/活動崩潰。Android:添加計時器使其崩潰

這裏是代碼:

import android.app.Activity; 
import android.graphics.Point; 
import android.os.Bundle; 
import android.view.Display; 
import android.view.View; 
import android.widget.Button; 

public class Testing extends Activity{ 

Timer timer = new Timer(); 

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

    final Button bt = (Button)findViewById(R.id.testButton); 

    bt.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      timer.scheduleAtFixedRate(new TimerTask(){ 
       @Override 
       public void run() { 
        float btLoc = bt.getX(); 
        bt.setX(btLoc+= 50); 
       } 
      }, 2000, 2000); 


     } 
    }); 
} 

這同一段代碼,沒有移動定時器之前工作過的按鈕。我不知道爲什麼在執行onClick(View v)時程序崩潰。

(對不起,我的英語)

+2

的_LogCat_跟蹤會給你爲什麼程序是_ 「破碎」 _暗示.. 。 –

+0

即時通訊android如何使用LogCat? – samy

+0

如果您正在使用_Eclipse_,則會顯示一個_LogCat_窗口,其中顯示設備中所有記錄的項目。 –

回答

1

使用runOnUiThread從非UI線程更新UI:

@Override 
public void onClick(View v) { 
    timer.scheduleAtFixedRate(new TimerTask(){ 
    @Override 
     public void run() { 

     Testing.this.runOnUiThread(new Runnable() { 
      public void run() { 
      //update ui here 
       float btLoc = bt.getX(); 
       bt.setX(btLoc+= 50); 
     } 
     }); 
     } 
    }, 2000, 2000); 

    } 
}); 
+0

謝謝,它工作:) – samy