本文介绍了使用Handler Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种是使用处理程序的更好方法.任何优势.我遇到的所有示例似乎都提供了内联版本.

在类中使用实现Handler.Callback并实现接口方法.

使用内联代码版本

private Handler mHandler = new Handler(){ ....};
解决方案

常用术语或这些内联类定义是匿名类.

您可以在 Java/Android:匿名本地类与命名类

基本上,主要区别在于可读性,编码速度,重用性和范围.

从资源的角度来看,匿名类的创建可能会导致垃圾收集器的开销,如避免创建不必要的对象.我不确定匿名类创建的确切细节,但是,在类上实现接口更有效是合乎逻辑的.

@WilliamTMallard提供了要做什么的示例.在他的示例中,应该在类上实现一个长且语法复杂的处理程序,而不是匿名处理程序,因为在内联定义时很难读取和编辑.

Which is the better way to use a handler. Any advantages. All examples I have come across seem to give the inline version.

Using implements Handler.Callback in the class and implementing interface method.

or

Using inline code version

private Handler mHandler = new Handler(){ ....};
解决方案

The common term or these inline class definitions is Anonymous Classes.

You can read more about the discussion on these in Java/Android: anonymous local classes vs named classes

Essentially the main differences are readbility, speed of coding, re-use and scope.

From a resource point of view the anonymous class creation may cause an overhead in the garbage collector as discussed in Avoid Creating Unnecessary Objects. I am not certain on the exact details of anonymous class creation, however, it is logical that implementing the interface on the class is more efficient.

@WilliamTMallard has provided an example of what NOT to do. In his example, a long and syntacticly complex handler should be implementented on the class rather than anonymous handler because it is harder to read and edit when defined inline.

这篇关于使用Handler Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:57
查看更多