【问题标题】:Most Performant Android ViewGroup to Use For Independantly Positioned Children? - RelativeLayout vs FrameLayout用于独立定位的孩子的最高性能 Android ViewGroup? - 相对布局与框架布局
【发布时间】:2014-03-10 15:25:24
【问题描述】:

我不是 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>

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

【问题讨论】:

    标签: android performance android-layout


    【解决方案1】:

    简答

    鉴于您提供的信息,FrameLayout 很有可能表现得更好。您可能已经在观看 (Adam Powell quote in Google I/O 2013 conference) 时了解到,

    [...] RelativeLayouts 将多次测量子视图,以解决您给它的一些约束。因此,通用是有成本的 [...]

    根据我的阅读和理解,这并不能保证,这取决于你给它的限制。

    长答案

    这真的取决于

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

    这个post,如果你还没有读过,它讨论了如何使用RelativeLayout 而不是LinearLayout 来删除一个层次结构级别,这可以节省列表中的加载时间。

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

    [...] 我有两个 ImageViews 我想完全独立地定位 [...] 我不想将孩子们相对于彼此组织起来

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

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

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

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

    我们开始将LinearLayout 替换为RelativeLayout。结果:没有明显的改善——相当或可能更糟。

    由于该布局相当复杂,添加更多相互嵌入的RelativeLayouts 只会增加为单次绘制进行的onMeasure() 调用。

    即使是一个小的循环 ProgressBar 现在也会通过多个度量调用向 UI 线程发送垃圾邮件,因为它位于其中一个嵌入式 RelativeLayout 中,触发了对整个视图的重新计算。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2014-02-14
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多