嗨抱歉我的英语! :) 我希望在3秒后通过随机数更改文本视图的文本,但它只是显示最后一个数字而我没有看到文本视图中的最后一个数字
我该怎么办?
谢谢...:)
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class TestActivity extends Activity {
int rand;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtShow = (TextView) findViewById(R.id.txtShow);
Handler handler = new Handler();
for (int i = 0; i < 5; i++)
{
rand = (int) (Math.random() * 9);
handler.postDelayed(new Runnable() {
@Override
public void run() {
txtShow.setText("" + rand);
}
}, 3000);
}
}
}
答案 0 :(得分:1)
公共类TestActivity扩展了Activity {
int rand;
int counter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txtShow = (TextView) findViewById(R.id.txtShow);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (counter > 4) {
handler.removeCallbacks(this);
return;
}
++counter;
rand = (int) (Math.random() * 9);
txtShow.setText("" + rand);
handler.postDelayed(this, 3000);
}
}, 3000);
}
}
当计数器达到5时,removeCallbacks
取消处理程序队列中仍然存在的所有可运行程序并返回。否则计数器增加,handler.postDelayed
将runnable添加到处理程序队列
答案 1 :(得分:0)
我认为这应该有效。
private Handler handler;
private TextView txt;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler = new Handler();
txt = (TextView) findViewById(R.id.txt);
new Thread(new Task()).start();
}
class Task implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 5; i++) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
int rand = (int) (Math.random() * 9);
txt.setText("" + rand);
}
});
}
}
}
答案 2 :(得分:0)
问题在于,正在更改Runnable
的所有TextView
正在紧接着执行;变化太快,以至于您无法看到中间值,而只能看到最终值。
要解决您的问题,请将postDelayed()
的延迟从3000
更改为3000 * i
。这将确保更新在每个之间间隔3秒,而不是仅在onCreate()
完成后3秒执行(现在是)。
对于类似的内容,您可能还需要查看Timer
(http://developer.android.com/reference/java/util/Timer.html)