我想寫一個實時計數器。我試圖使用線程,但是android警告我只有活動線程可能觸及視圖。我發現了一個解決方案與runOnUiThread
,但它不工作太runOnUiThread,更改TextView
public class CounterInRealTimeExampleActivity extends Activity {
private TextView textView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
textView = new TextView(this);
textView.setTag(new Integer(0));
layout.addView(textView);
setContentView(layout);
runOnUiThread(new Runnable() {
@Override
public void run() {
//while(true)
{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
increment();
}
}
});
}
public void increment() {
textView.setTag(new Integer((Integer)textView.getTag())+1);
textView.setText(Integer.toString((Integer)textView.getTag()));
}
}
你嘗試http://developer.android.com/reference/android/os/CountDownTimer.html? – Calvin 2012-03-17 13:43:42