我尝试在textwiew中打印正在更改的消息。 我这样做的问题是应用程序正在等待循环结束以产生结果。
public class Testloop extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testloop);
String message = "test : ";
for(int x = 1; x < 20; x = x + 1) {
message +=x;
int timeInMills = 1000; // time in ms
SystemClock.sleep(timeInMills);
TextView textView = (TextView) findViewById(R.id.txte);
textView.setText(message);
}
}
答案 0 :(得分:0)
onCreate方法不适合这个。循环将在活动甚至可见之前完成,您设置的最后一个字符串将是唯一显示的字符串。尝试使用带有处理程序的Runnable,如下所示:
private Handler handler = new Handler();
handler.postDelayed(runnable, 100);
这将告诉runnable在100ms内运行。然后像这样创建runnable:
private Runnable runnable = new Runnable() {
@Override
public void run() {
//Set your text here
textView.setText(message);
// here you set the runnable to run again in 100ms
handler.postDelayed(this, 100);
}
};
每次运行runnable时,将消息字符串放在一个数组中并通过它进行索引。