性能最佳的Android ViewGroup可用于独立定位的儿童吗? - RelativeLayout vs FrameLayout

时间:2014-03-10 15:25:24

标签: android performance android-layout

我不是Android专家,但我知道有关正确使用LinearLayout和RelativeLayout的讨论,保持视图层次结构尽可能小,避免不必要的onMeasure()传递等。

让我们想象一下,我有两个想要完全独立定位的ImageView,第一个位于父级中心,第二个位于父级左下角。 (请注意,这是一个非常复杂的现实生活要求的例子)。

解决这个问题的显而易见的方法是使用RelativeLayout ...

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/first_image" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="true"
        android:layout_alignBottom="true"
        android:src="@drawable/second_image" />

</RelativeLayout>

然而有些事情告诉我,在这种情况下,RelativeLayout不合适,因为我不想将孩子相对于彼此组织起来。我想做的就是根据父级定位子项,我想知道使用RelativeLayout是否会导致一些我不需要的不必要的布局计算。

我想知道是否还有其他ViewGroup类型会表现更好?完全有可能用FrameLayout实现我想要的东西,但是我不知道这是否更具性能或者我是否滥用了FrameLayout的意图等等......

<FrameLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/first_image" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right|bottom"
        android:src="@drawable/second_image" />

</FrameLayout>

也许还有另一种我不知道的布局类型?

1 个答案:

答案 0 :(得分:3)

简短回答

根据您提供的信息,FrameLayout很有可能表现得更好。你可能已经学会了观察(Adam Powell quote in Google I/O 2013 conference),

  

[...] RelativeLayouts将多次测量子视图,以解决您给出的一些限制。因此,通用具有成本[...]

从我阅读和理解的内容来看,这并不能保证,这取决于你给出的限制。

答案很长

这取决于

我们都阅读Romain Guy blog post : Android Layout Tricks #1said that most people misinterpret postpost并开始在任何地方使用RelativeLayout

此{{3}},如果您还没有阅读,请讨论如何使用RelativeLayout而不是LinearLayout删除一个层次结构级别,从而节省列表中的加载时间。

基本上,这意味着如果你不需要它们,就像你自己描述的那样

  

[...]我有两个想要完全独立定位的ImageView [...]我不想把孩子们相对于彼此组织起来

因为这个原因你不应该使用它们。

具体示例:“如果您不需要,请不要使用它们。”

例如,在我们的一个应用程序中,我们在运行Gingerbread的设备上遇到严重的性能问题 - 我们希望支持它们。

我们最复杂的布局涉及一个垂直ScrollView,附加到当前活动,其中我们有几个容器和一个HorizontalScrollView,它们显示复杂{{1}中包含的图像和信息}。

我们开始将LinearLayout替换为LinearLayout。结果:没有明显的改善 - 相当于或者更糟。

由于该布局相当复杂,因此在彼此中添加更多RelativeLayout只会增加为单次绘制所做的RelativeLayout次调用。

即使是一个小型循环onMeasure()现在也在用多个度量调用发送垃圾邮件,因为它位于其中一个嵌入式ProgressBar中,触发了整个视图的重新计算。

相关问题