刚刚在研究Android中的Threads(我也是Threads时期的新手)。我正在查看其他各种帖子,但仍需要一些说明。我使用 HelloWorld 保持简单。我想要的是显示消息:“Hello World this is a thread”,每个单词每隔 1 秒显示一次。想到使用带有消息的字符串数组。然后在线程中使用for循环遍历每个元素。我很确定我理解我的问题的逻辑——因为整个循环在延迟时间范围内执行。谁能告诉我如何解决这个问题,以便以 1 秒的间隔显示每个元素?这是我的代码:
public class HelloWorld extends Activity {
Handler m_handler;
Runnable m_handlerTask ;
private TextView hello;
private String[] HelloWorld = {
"Hello",
"World",
"This",
"Is",
"A",
"Thread",
};
int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world);
hello = (TextView) findViewById(R.id.hello);
m_handler = new Handler();
m_handlerTask = new Runnable()
{
@Override
public void run() {
if(i<HelloWorld.length-1)
{
hello.append(HelloWorld[i]);
hello.setText("\n");
i++;
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
m_handler.removeCallbacks(m_handlerTask);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hello_world, menu);
return true;
}
最佳答案
使用线程
Thread thread;
private String[] HelloWorld = {
"Hello",
"World",
"This",
"Is",
"A",
"Thread",
};
int i=0;
在你的 onCreate() 中
thread = new Thread(new Runnable(){
@Override
public void run(){
for( i = 0; i < HelloWorld.length; i++){
runOnUiThread(new Runnable(){
@Override
public void run(){
hello.append(HelloWorld[i]);
hell0.append(" ");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread.start();
我建议你使用 Handler
Handler m_handler;
Runnable m_handlerTask ;
private String[] HelloWorld = {
"Hello",
"World",
"This",
"Is",
"A",
"Thread",
};
int i=0;
在你的 onCreate() 中
m_handlerTask = new Runnable()
{
@Override
public void run() {
if(i<HelloWorld.length)
{
hello.append(HelloWorld[i]);
hello.append(" ");
i++;
}
else
{
m_handler.removeCallbacks(m_handlerTask);
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
不需要时停止运行
m_handler.removeCallbacks(m_handlerTask);
关于android - Android 中的基本线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16485276/