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");
}
});
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?
If you really have to do this from multiple classes, you could create a public static method that will run a runnable on the main thread. Something like this:
You call it by doing something like this:
If you're calling the same UI method repeatedly, you could streamline the client code by creating the
Runnable
in a method:Then your client code would simply call
updateUi("changetext")
. (This code assumes thatui
is final. If not, you could pass in a final reference.)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.