问题描述
我使用这个code,以显示消息:
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();
}
});
常见的一类矿井,和getHandler()将返回在活动创建的处理程序。这样我可以从外面打电话的活动吐司。
这是一个很好的形式给出,它工作得很好,但我不知道是否有另一种方式来使C一点点清洁剂$ C $ /短。
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.
是这样的:
Common.run({
Toast.makeText(Common.getContext(), "Text...", Toast.LENGTH_SHORT).show();
});
和的run()方法应该封装code作为内一个Runnable参数传递。
And the run() method should encapsulate the code passed as argument inside a Runnable.
AFAIK这就是所谓的闭包,它可能在Javascript。
AFAIK this is called closure and it's possible in Javascript.
祺!
推荐答案
这是你可以用Java做的最好的。您只能传递对象(和标量)左右,所以你要么必须创建一个类实现Runnable,或者你正在做的,现在这就是创建实现Runnable的匿名对象实例。
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.
这篇关于传递code作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!