Java setText未在Runnable中更新
我正在构建一个Android应用程序。应用程序正在从服务器提取数据,应该使用该数据更新TextView live。以下是我的流程代码,省略了不必要的细节:Java setText未在Runnable中更新,java,android,multithreading,textview,runnable,Java,Android,Multithreading,Textview,Runnable,我正在构建一个Android应用程序。应用程序正在从服务器提取数据,应该使用该数据更新TextView live。以下是我的流程代码,省略了不必要的细节: public class MainActivity { 从OnCreate类启动Runnable: protected void OnCreate(...) { ... Thread connect = new Thread(runnable); connect.start(); } 可运
public class MainActivity
{
从OnCreate类启动Runnable:
protected void OnCreate(...)
{
...
Thread connect = new Thread(runnable);
connect.start();
}
可运行类的代码:
Runnable runnable = new Runnable()
{
public void run()
{
...(setting up server input stuff)
final TextView strDisplay = (TextView)findViewById(R.id.stringDisplay);
while (!Thread.currentThread ().isInterrupted())
{
try
{
final String serverInput = subscriber.recvStr(); //receiving server input
strDisplay.post(new Runnable()
{
public void run()
{
//Updating TextView "strDisplay" with the latest server data
strDisplay.setText(serverInput);
}
});
}
catch...
}
}
};
}
但是,当我运行此命令时,只有它接收到的第一个服务器输入才会显示在TextView中,然后,尽管有更多的输入进来(我用日志检查过),TextView不会更新。在控制台中,我在打印第一个输入后读取“onFinishInput”,然后输入流在控制台上启动。我原以为启动一个新的Runnable会允许它进行更新,但它什么也没做 用户界面只能由UI线程更新。您需要一个处理程序来发布到UI线程:
事实证明,我发布的这段代码确实有效。 关键部分是:
`strDisplay.post(new Runnable()
{
public void run()
{
//Updating TextView "strDisplay" with the latest server data
strDisplay.setText(serverInput);
}
});`
我的程序可能有另一个错误,但这就是我目前的情况,它工作得很好:-)我希望这能帮助别人解决问题 我不确定您是否正在调用它,但从这里看,您似乎没有调用runnable.run();