我正在尝试制作一个从 5 到 1 的简单计数器,并在每秒后更新视图。我试过在没有处理程序的情况下只用一个简单的循环来做这件事,但它只是在等待后向我显示 1 或者它强制关闭。我也尝试过弄乱runOnUIThread
和线程,但我错过了一些东西。
这是我的代码:
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);
}
}