【问题标题】:Which way of creating view is faster in android XML or drawing on Canvas [duplicate]在android XML中或在Canvas上绘制哪种视图更快[重复]
【发布时间】:2012-12-01 18:18:39
【问题描述】:
【问题讨论】:
标签:
android
android-custom-view
【解决方案1】:
如果您谈论的是性能,这取决于您使用 onDraw() 的效率。
当您在 XML 中定义视图时,您所做的只是告诉布局膨胀器创建视图类型类的实例并将其初始属性设置为您定义的 XML 属性。然后,当视图被绘制时,猜猜是什么——它调用了 onDraw() 来绘制视图。
因此,如果您扩展 View 并覆盖 onDraw() 并使用与超类所使用的完全相同的方法来绘制视图,则不会有性能差异。
所以,答案(如果您确实在询问性能)是“取决于”。
同样,正如您的 onDraw() 可能效率低下一样,您的布局设计也可能效率低下。冗余视图组,如嵌套的 LinearLayouts、RelativeLayouts 等会对性能产生非常大的负面影响。布局层次结构查看器是一个很好的了解工具。
【解决方案2】:
Ollie C https://stackoverflow.com/a/9827887/603233 的好回答:
XML 的优点是:
1. Ability to use layout editors (Eclipse)
2. Easier to preview layouts
3. Possible to benefit from auto-localisation of layouts
4. Easily maintain different parallel layouts for difference devices (screens)
5. Can get a sense of the layout by looking at it (easier than code)
6. Easy to break layouts down into pieces (fragments, includes, etc) to remove duplication
7. Keeps a separation between the visual design, and the functionality behind it