更新 UI / runOnUiThread / Final 变量:如何编写精益代码,在从另一个线程调用时执行 UI 更新
当我发现像 WinForms 一样,Android 需要从主线程进行 UI 更新时,我一直在阅读 UI 更新(太糟糕了,我希望有人能够一劳永逸地解决这个恼人的问题)。
无论如何,我需要将其传递给 UI 线程。一些人建议使用 runOnUiThread 方法,如果不是随后出现的令人恼火的“最终”方法,这可能会起作用。
我有一个接口,其方法我无法更改。它看起来像这样:
@Override
public void connStateChange(ClientHandler clientHandler)
当我的连接状态(网络)发生变化时,会调用该方法。当我这样做时,我需要做一些事情,在本例中,它是向 TextView 添加一些文本。
所以我尝试了这个,但当然变量“clientHandler”不是最终的:
@Override
public void connStateChange(ClientHandler clientHandler) {
runOnUiThread(new Runnable()
{
public void run()
{
tv.append(clientHandler.getIP() + ", " + clientHandler.state.toString() + "\n");
if (clientHandler.state == State.Connected)
{
tv.append("Loginserver hittad");
}
}
});
}
我如何以一种漂亮、干净和高效的方式在此示例中编写代码来更新 UI?我需要访问我的所有变量等......
I have been reading up on the UI updating when I found out that, like WinForms, Android need to do UI updates on from the main thread (too bad, I was hoping someone could once and for all solve that irritating problem).
Anyways, I need to pass that to the UI thread. Some suggest the use of the runOnUiThread method and that might have worked, if it wasn't for that irritating "final" that then came into play.
I have an Interface, with a method I cannot change. It looks like this:
@Override
public void connStateChange(ClientHandler clientHandler)
That method is called when I get a change in the connection status (network). When I do, I need to do some stuff, and in this case it is adding some text to a TextView.
So I tried this, but of course the variable "clientHandler" isn't final:
@Override
public void connStateChange(ClientHandler clientHandler) {
runOnUiThread(new Runnable()
{
public void run()
{
tv.append(clientHandler.getIP() + ", " + clientHandler.state.toString() + "\n");
if (clientHandler.state == State.Connected)
{
tv.append("Loginserver hittad");
}
}
});
}
How do I in a nice, clean and efficient way write code in this example to update the UI? I need access to all my variables etc...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试一下:
顺便说一句,如果您不在方法中声明匿名类,而是在方法外声明内部类,则代码会变得更具可读性。将其视为模式命令。
更干净和可重用的代码示例。
尽管 Runnable 实现本身有点膨胀,但代码变得更加可重用且易于阅读。
Try it:
By the way, code becomes more readable, if you declare not anonim class right in the method, but declare inner class out of methods. Consider it as pattern Command.
Example of more clean and reusable code.
Though the Runnable implementation itself was inflated a little, code became more re-usable and easy to read.