1
我試圖做一個簡單的計數器,從5計數到1並在每秒鐘後更新視圖。我試過沒有處理程序,只是用一個簡單的循環,但它只是在等待或強制關閉後顯示給我1。我已經嘗試了runOnUIThread
和線程,但我錯過了一些東西。使用處理程序更新TextView
這裏是我的代碼:
package com.ammad.test;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class Main extends Activity {
TextView tv;
Button b1;
Handler mHandler;
int i = 5;
private Runnable runnable;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvShow);
b1 = (Button) findViewById(R.id.bt1);
runnable = new Runnable() {
public void run() {
// do your stuff - don't create a new runnable here!
tv.setText(String.valueOf(i));
i--;
mHandler.postDelayed(runnable, 500);
}
};
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mHandler.post(runnable);
mHandler.removeCallbacks(runnable);
}
});
}
public void doTheLoop() {
/*
* runOnUiThread(new Runnable() {
*
* public void run() { for (int i = 5; i >= 1; i--) { // TODO
* Auto-generated method stub tv.setText(Integer.toString(i)); for (int
* j = 0; j < 200000; j++) ; } }
* `enter code here`
* });
*/
// mHandler.post(runnable);
}
}
thans alot dude ...你是一個救星...我一直在嘗試做同樣的事情,但我認爲我錯過了這個mTextView.post ... thanx了.. – Ammad 2012-07-21 12:29:52