问题描述
我的问题似乎很简单,但逻辑看来我似乎不对。
我试图使用UI线程运行其他类的方法。我可以通过这样包装我的方法来做到这一点
My question seems very simple but i can't seem to the logic right.Am trying to run methods from other classes using the UI thread. I could do this this simply by wrapping my methods like this
runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
ui.myMethod("changetext");
}
});
但我的目标是要创建一个包装方法的类在UI线程上,因为在单个类中几乎有5次 runOnUiThread()
似乎很麻烦。
but my goal is to have a class that wraps methods to be run on the UI thread as having runOnUiThread()
almost 5 times in a single class seems very untidy. Any pointers?
推荐答案
如果重复调用相同的UI方法,则可以通过创建<$来简化客户端代码。 c $ c> Runnable 的方法:
If you're calling the same UI method repeatedly, you could streamline the client code by creating the Runnable
in a method:
private void updateUi(final String message) {
runOnUiThread(new Runnable() {
public void run() {
ui.myMethod(message);
}
});
}
然后,您的客户代码只需调用 updateUi( changetext)
。 (此代码假定 ui
是最终的。如果不是,则可以传递最终引用。)
Then your client code would simply call updateUi("changetext")
. (This code assumes that ui
is final. If not, you could pass in a final reference.)
如果您每次都调用一个不同的UI方法,但这并不会给您带来任何好处,因为您需要为每个UI方法使用单独的更新方法。您现有的代码非常优雅。
If you're calling a different UI method every time, this doesn't gain you anything as you'd need a separate update method for each UI method. Your existing code is as elegant as it gets.
这篇关于在UI线程上运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!