我想打印如下:
for(int i=0;i<should be infinite;i++)
{
Data is Loading.
sleep(100);
Data is Loading..
sleep(100);
Data is Loading...
sleep(100);
}
以下是无效的代码
package com.queen.a01_simple_request;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for (; ; ) {
try {
textView.setText("Downloading The File");
Thread.sleep(1000);
textView.setText("Downloading The File.");
Thread.sleep(1000);
textView.setText("Downloading The File..");
Thread.sleep(1000);
textView.setText("Downloading The File...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
现在,这应该循环无限。点应该永远一个接一个地改变。我不想像i <1000那样设置值。我想实现这一点。
答案 0 :(得分:1)
basic for statement的前3个“部分”是可选的:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
所以,虽然看起来很奇怪,但这是一个有效的for循环(永远不会做任何事情):
for (;;);
在您的情况下,只需省略Expression
:
for (int i = 0; ; i++) { ... }
答案 1 :(得分:0)
for(;;){
{
try{
Data is Loading.
Thread.sleep(100);
Data is Loading..
Thread.sleep(100);
Data is Loading...
Thread.sleep(100);
}catch(Exception ignored){}
}
编辑: 如果你在主线程(UI线程)上执行此操作,它将冻结应用程序,你必须在后台启动循环,如下所示:
new Thread(new Runnable(){
@Override
public void run(){
for(;;){
try{
Data is Loading.
Thread.sleep(100);
Data is Loading..
Thread.sleep(100);
Data is Loading...
Thread.sleep(100);
}catch(Exception ignored){}
}
}
}
答案 2 :(得分:-1)
试试这个:
while(true){
code...
}