I’m using this code to show messages:
Common.getHandler().post(new Runnable(){
public void run(){
Toast.makeText(Common.getContext(), "Text...", Toast.LENGTH_SHORT).show();
}
});
Common is a class of mine, and getHandler() will return a handler created in an activity. This way I can call Toast from outside activities.
This is a good aproach, and it works fine, but I’m wondering if there is another way to make that code a little bit cleaner/shorter.
Something like:
Common.run({
Toast.makeText(Common.getContext(), "Text...", Toast.LENGTH_SHORT).show();
});
And the run() method should encapsulate the code passed as argument inside a Runnable.
AFAIK this is called closure and it’s possible in Javascript.
Regards!
This is about the best you can do in Java. You can only pass objects (and scalars) around, so you either have to create a class implementing Runnable, or do what you are doing now which is to create an anonymous object instance implementing Runnable.