我正在创建一个示例应用,我希望每秒更改一次TextVeiw值。
TextView值应该每秒更改一次。
执行此任务我尝试了以下代码:
但此代码不会继续更改文本值,只会在应用开始或屏幕旋转时更改。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Boolean b = true;
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "2345u8", "9654", "987650", };
Random generator = new Random();
final int random = generator.nextInt(str.length);
Thread t = new Thread() {
@Override
public void run() {
try {
while (b != false) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
// update TextView here!
tv.setText(str[random]);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
}
我也试过这段代码: 但是此代码崩溃应用程序
private Timer timer = new Timer();
private TimerTask timerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "2345u8", "9654", "987650", };
Random generator = new Random();
final int random = generator.nextInt(str.length);
timerTask = new TimerTask() {
@Override
public void run() {
// refresh your textview
tv.setText(str[random]);
}
};
timer.schedule(timerTask, 0, 1000);
}
答案 0 :(得分:2)
尝试以下代码段
final Handler h = new Handler();
h.post(new Runnable() {
@Override
public void run() {
long millis =(long)currentTime();
dateAndTime.setText(getDate(millis, "dd/MM/yyyy hh:mm:ss.SSS"));
h.postDelayed(this, 1000);
}
});
答案 1 :(得分:1)
final TextView tv = (TextView) this.findViewById(R.id.textView1);
final String[] str = new String[] { "897451", "34232", "33432",
"46867", "54554", "6756", "56r7", "23458", "9654", "987650", };
// //
final Handler h = new Handler();
h.post(new Runnable() {
@Override
public void run() {
Random generator = new Random();
final int random = generator.nextInt(str.length);
tv.setText(str[random]);
h.postDelayed(this, 1000);
}
});
// //