1
我正在創建示例應用程序,我希望每秒更改一次TextVeiw值。每秒更改TextView值(Android)
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);
}