Kyl*_*Yeo 12 implementation android loops while-loop logcat
我无法理解android中while循环的实现.
每当我在onCreate()bundle中实现while循环时,(代码如下所示)
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView=(TextView)findViewById(R.id.TextView);
while (testByte == 0)
updateAuto();
}
Run Code Online (Sandbox Code Playgroud)
什么都没有启动,程序在一段时间后进入"悬挂"状态,我无法理解为什么.Testbyte如下:
byte testByte == 0;
Run Code Online (Sandbox Code Playgroud)
并且updateAuto()应该每1秒更新一次代码并显示在textView部分内.我一直在updateAuto()里面使用setText,如下所示,一切正常,但是一旦我实现了while循环,我看到的是一个黑屏,然后是一个选项,由于它"没有响应"几秒后强制关闭.
TextView.setText(updateWords);
Run Code Online (Sandbox Code Playgroud)
我已将其更改为按钮格式(意味着我必须单击按钮才能自动更新),但我希望它更新自己而不是手动点击它.
我是以错误的方式实现while循环吗?
我也试过在单独的函数中调用while循环,但它仍然给我黑屏的虚无.
我一直在阅读有关Handler服务的内容......它有什么作用?Handler服务能否TextView以更安全或更高效的方式更新我的服务?
非常感谢,如果有人能就我应该做些什么给出一些指示.
Zai*_*ani 33
振作起来.并尝试密切关注,这将作为开发者非常宝贵.
虽然循环真的应该只在一个单独的线程中实现.单独的线程就像在您的应用中运行的第二个进程.强制关闭的原因是因为你在UI线程中运行循环,使得UI无法执行任何操作,除了通过该循环.您必须将该循环放入第二个Thread中,以便UI Thread可以自由运行.线程化时,除非您在UI线程中,否则无法更新GUI.以下是在这种情况下如何完成.
首先,创建一个Runnable,它将包含在其run方法中循环的代码.在该Runnable中,您必须创建一个发布到UI线程的第二个Runnable.例如:
TextView myTextView = (TextView) findViewById(R.id.myTextView); //grab your tv
Runnable myRunnable = new Runnable() {
@Override
public void run() {
while (testByte == 0) {
Thread.sleep(1000); // Waits for 1 second (1000 milliseconds)
String updateWords = updateAuto(); // make updateAuto() return a string
myTextView.post(new Runnable() {
@Override
public void run() {
myTextView.setText(updateWords);
});
}
}
};
Run Code Online (Sandbox Code Playgroud)
接下来,使用Runnable创建您的线程并启动它.
Thread myThread = new Thread(myRunnable);
myThread.start();
Run Code Online (Sandbox Code Playgroud)
您现在应该看到您的应用程序循环而没有强制关闭.