Custom ViewGroups

Android provides a few ViewGroups like LinearLayout, RelativeLayout, FrameLayout to position child Views. These general purpose ViewGroups have quite a lot of options in them. For e.g, LinearLayout supports almost all (except for wrapping) features of HTML Flexbox. It also has options to show dividers in between Views, and measure all children based on the largest child. RelativeLayout works as a constraint solver. These layouts are good enough to start with. But do they perform well when your app has complex UI?

ViewGroup with a ProfilePhoto, Title, Subtitle and Menu button.

The above layout is pretty common in the Facebook app. A profile photo, a bunch of Views stacked vertically to its right, and an optional view on the far right. Using vanilla ViewGroups, this layout can be achieved using a LinearLayout of LinearLayouts or a RelativeLayout. Let’s take a look at the measure calls happening for these two layouts.

Here’s an example LinearLayout of LinearLayout file.

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ProfilePhoto
            android:layout_width="40dp"
            android:layout_height="40dp"/>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <Title
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

            <Subtitle
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        </LinearLayout>

        <Menu
            android:layout_width="20dp"
            android:layout_height="20dp"/>

    </LinearLayout>

And the measure pass happens as follows on a Nexus 5.

> LinearLayout [horizontal]       [w: 1080  exactly,       h: 1557  exactly    ]
        > ProfilePhoto                [w: 120   exactly,       h: 120   exactly    ]
        > LinearLayout [vertical]     [w: 0     unspecified,   h: 0     unspecified]
            > Title                   [w: 0     unspecified,   h: 0     unspecified]
            > Subtitle                [w: 0     unspecified,   h: 0     unspecified]
            > Title                   [w: 222   exactly,       h: 57    exactly    ]
            > Subtitle                [w: 222   exactly,       h: 57    exactly    ]
        > Menu                        [w: 60    exactly,       h: 60    exactly    ]
        > LinearLayout [vertical]     [w: 900   exactly,       h: 1557  at_most    ]
            > Title                   [w: 900   exactly,       h: 1557  at_most    ]
            > Subtitle                [w: 900   exactly,       h: 1500  at_most    ]

The ProfilePhoto and the Menu are measured only once as they have an absolute width and height specified. The vertical LinearLayout gets measured twice here. During the first time, the parent LinearLayout asks it to measure with an UNSPECIFIED spec. This cause the vertical LinearLayout to measure its children with UNSPECIFIED spec. And then it measures its children with EXACTLY spec based on what they returned. But it doesn’t end there. Once after measuring the ProfilePhoto and the Menu, the parent knows the exact size available for the vertical LinearLayout. This causes the second pass where the Title and Subtitle are measured with an AT_MOST height. Clearly, every TextView (Title and Subtitle) is measured thrice. These are expensive operations as Layouts are created and thrown away during the second pass. If we want a better performing ViewGroup, cutting down the measure passes on the TextViews is the first thing to do.

Does a RelativeLayout work better here?

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

        <ProfilePhoto
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"/>

        <Menu
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"/>

        <Title
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/profile_photo"
            android:layout_toLeftOf="@id/menu"/>

        <Subtitle
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/title"
            android:layout_toRightOf="@id/profile_photo"
            android:layout_toLeftOf="@id/menu"/>

    </RelativeLayout>

And the measure pass looks like this.

> RelativeLayout                  [w: 1080  exactly,   h: 1557  exactly]
        > Menu                        [w: 60    exactly,   h: 1557  at_most]
        > ProfilePhoto                [w: 120   exactly,   h: 1557  at_most]
        > Title                       [w: 900   exactly,   h: 1557  at_most]
        > Subtitle                    [w: 900   exactly,   h: 1557  at_most]
        > Title                       [w: 900   exactly,   h: 1557  at_most]
        > Subtitle                    [w: 900   exactly,   h: 1500  at_most]
        > Menu                        [w: 60    exactly,   h: 60    exactly]
        > ProfilePhoto                [w: 120   exactly,   h: 120   exactly]

As I previously mentioned, RelativeLayout measures by solving constraints. In the above layout, ProfilePhoto and the Menu are not dependent on any other siblings, and hence they are measured first (with an AT_MOST height). Then the Title (2 constraints) and Subtitle (3 constraints) are measured. At this point all Views know how much size they want. RelativeLayout uses this information for a second pass to measure the Title, Subtitle, Menu and ProfilePhoto. Again, every View is measured twice, thus being sub-optimal. If you compare this with LinearLayout example above, the last MeasureSpec used on all the leaf Views are the same — thus providing the same output on the screen.

How can we cut down the measure pass happening on the child Views? Do creating a custom ViewGroup help here? Let’s analyze the layout. The Title and Subtitle are always to the left of the ProfilePhoto and the right of the Menu button. The ProfilePhoto and the Menu button have fixed width and height. If we solve this manually, we need to calculate the size of the ProfilePhoto and the Menu button, and use the remaining size to calculate the Title and the Subtitle — thus performing only one measure pass on each View. Let’s call this layout ProfilePhotoLayout.

public class ProfilePhotoLayout extends ViewGroup {

        private ProfilePhoto mProfilePhoto;
        private Menu mMenu;
        private Title mTitle;
        private Subtitle mSubtitle;

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            // 1. Setup initial constraints.
            int widthConstraints = getPaddingLeft() + getPaddingRight();
            int heightContraints = getPaddingTop() + getPaddingBottom();
            int width = 0;
            int height = 0;

            // 2. Measure the ProfilePhoto
            measureChildWithMargins(
                mProfilePhoto,
                widthMeasureSpec,
                widthConstraints,
                heightMeasureSpec,
                heightConstraints);

            // 3. Update the contraints.
            widthConstraints += mProfilePhoto.getMeasuredWidth();
            width += mProfilePhoto.getMeasuredWidth();
            height = Math.max(mProfilePhoto.getMeasuredHeight(), height);

            // 4. Measure the Menu.
            measureChildWithMargins(
                mMenu,
                widthMeasureSpec,
                widthConstraints,
                heightMeasureSpec,
                heightConstraints);

            // 5. Update the constraints.
            widthConstraints += mMenu.getMeasuredWidth();
            width += mMenu.getMeasuredWidth();
            height = Math.max(mMenu.getMeasuredHeight(), height);

            // 6. Prepare the vertical MeasureSpec.
            int verticalWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                MeasureSpec.getSize(widthMeasureSpec) - widthConstraints,
                MeasureSpec.getMode(widthMeasureSpec));

            int verticalHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                MeasureSpec.getSize(heightMeasureSpec) - heightConstraints,
                MeasureSpec.getMode(heightMeasureSpec));

            // 7. Measure the Title.
            measureChildWithMargins(
                mTitle,
                verticalWidthMeasureSpec,
                0,
                verticalHeightMeasureSpec,
                0);

            // 8. Measure the Subtitle.
            measureChildWithMargins(
                mSubtitle,
                verticalWidthMeasureSpec,
                0,
                verticalHeightMeasureSpec,
                mTitle.getMeasuredHeight());

            // 9. Update the sizes.
            width += Math.max(mTitle.getMeasuredWidth(), mSubtitle.getMeasuredWidth());
            height = Math.max(mTitle.getMeasuredHeight() + mSubtitle.getMeasuredHeight(), height);

            // 10. Set the dimension for this ViewGroup.
            setMeasuredDimension(
                resolveSize(width, widthMeasureSpec),
                resolveSize(height, heightMeasureSpec));
        }

        @Override
        protected void measureChildWithMargins(
            View child,
            int parentWidthMeasureSpec,
            int widthUsed,
            int parentHeightMeasureSpec,
            int heightUsed) {
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

            int childWidthMeasureSpec = getChildMeasureSpec(
                parentWidthMeasureSpec,
                widthUsed + lp.leftMargin + lp.rightMargin,
                lp.width);

            int childHeightMeasureSpec = getChildMeasureSpec(
                parentHeightMeasureSpec,
                heightUsed + lp.topMargin + lp.bottomMargin,
                lp.height);

            child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        }
    }

Let’s analyze this code. We start with the known constraints — padding on all sides. The other way to look at constraints is that this value provides the amount of a dimension — width/height — used currently. Android provides a helper method, measureChildWithMargins() to measure a child inside a ViewGroup. However, it always adds padding to it as a part of constraints. Hence we have to override it to manage the constraints ourselves. We start by measuring the ProfilePhoto. Once measured, we update the constraints. We do the same thing for the Menu. Now this leaves us with the amount of width available for the Title and the Subtitle. Android provides another helper method, makeMeasureSpec(), to build a MeasureSpec. We pass in the required size and mode, and it returns a MeasureSpec. In this case, we pass in the available width and height for the Title and Subtitle. With these MeasureSpecs, we measure the Title and Subtitle. At the end we update the dimension for this ViewGroup. From the steps it’s clear that each View is measured only once.

> ProfilePhotoLayout              [w: 1080  exactly,   h: 1557  exactly]
        > ProfilePhoto                [w: 120   exactly,   h: 120   exactly]
        > Menu                        [w: 60    exactly,   h: 60    exactly]
        > Title                       [w: 900   exactly,   h: 1557  at_most]
        > Subtitle                    [w: 900   exactly,   h: 1500  at_most]

Does it really provide performance wins? Most of the layout you see in Facebook app uses this layout, and has proved to be really effective. And, I leave the onLayout() as an exercise for the reader ;)

And oh, do you like solving such Android UI engineering problems? Facebook has openings for experts in this area. Apply here!

时间: 2024-10-08 15:02:39

Custom ViewGroups的相关文章

[UI]抽屉菜单DrawerLayout分析(一)

侧拉菜单作为常见的导航交互控件,最开始在没有没有android官方控件时,很多时候都是使用开源的SlidingMenu,一直没机会分析侧拉菜单的实现机理,本文将分析android.support.v4.widget.DrawerLayout的使用及实现.     官方介绍 DrawerLayout acts as a top-level container for window content that allows for interactive "drawer" views to

Android应用ViewDragHelper详解及部分源码浅析

[工匠若水 http://blog.csdn.net/yanbober 未经允许严禁转载,请尊重作者劳动成果.私信联系我] 1 背景 很久没有更新博客了,忙里偷闲产出一篇.写这片文章主要是去年项目中的一个需求,当时三下五除二的将其实现了,但是源码的阅读却一直扔在那迟迟没有时间理会,现在拣起来看看吧,否则心里一直不踏实. 关于啥是ViewDragHelper,这里不再解释,官方下面这个解释已经很牛逼了,如下: /** * ViewDragHelper is a utility class for

Android的ViewDragHelper源码解析

其实我想看的是DrawerLayout, 但发现DrawerLayout里面是使用了ViewDragHelper去实现. 谷歌比较早就放出这个类了,但ViewDragHelper是开发中很少用到一个类.顾名思义这是一个和拖曳触摸有关的类. 本着追根溯源的想法, 加上ViewDragHelper的源码也不算多,就决定将ViewDragHelper的源码看一遍.对实现原理了解下. 代码一千多行,看完还是需要点时间的. 因此不会逐一讲完, 当然下面也会放出该类源码的解析,注释中也有一些个人理解的点写在

一个千万量级的APP使用的一些第三方库

.背景 前段时间在调研第三方推送服务的时候,反编译了一部分市面上比较流行的APP.其中一个无论是在设计还是功能上都堪称典型,这款APP总用户数超千万(其官网数据),在国内某手机助手上支持率超97%.可见其受欢迎程度(APP的名字就不说了).反编译这个APP后发现其使用的第三方库也很有代表性.这里介绍下他们使用的这些第三方库,给需要的童鞋一些参考. 1.Android Design Support Library 这个并不是一个第三方库,是谷歌官方出的支持库.之所以列出来除了上面说的这个APP有使

滑动 ViewDragHelper DrawerLayout

参考:http://blog.csdn.net/lmj623565791/article/details/46858663 API文档:https://developer.android.google.cn/reference/android/support/v4/widget/ViewDragHelper.html 概述 官方在v4的支持包中提供了ViewDragHelper这样一个类来帮助我们方便的编写自定义ViewGroup ViewDragHelper is a utility clas

Adapter优化方案的探索

概要:使用Adapter的注意事项与优化方案本文的例子都可以在结尾处的示例代码连接中看到并下载,如果喜欢请star,如果觉得有纰漏请提交issue,如果你有更好的点子可以提交pull request.本文的示例代码主要是基于CommonAdapter这个库编写的,若你有其他的技巧和方法可以参与进来一起完善这篇文章.固定连接:https://github.com/tianzhijiexian/Android-Best-Practices/blob/master/2015.10/adapter/ad

【Android界面实现】ZListView,一个最强大的刷新、加载、滑动删除的ListView控件(二)

转载请注明出处:http://blog.csdn.net/zhaokaiqiang1992 我们接着上篇的文章说,在前一篇文章中,我们学习了ZListView的使用,这一篇就开始说一些干货了,本篇文章将介绍ZListView的实现原理. 其实说是ZListView的实现原理,不如说是ZSwipeItem的实现原理,因为ZSwipeItem才是滑动的关键所在. ZSwipeItem的滑动,主要是通过ViewDragHelper这个类实现的.在接触这个项目之前,我没听过,也从来碰到过这个类,View

开发技术前线 第十一期

Android 领域 技术文章 Code Review最佳实践 听FackBook工程师讲Custom ViewGroups 详解Dagger2 Android进行单元测试难在哪-part3 Android-Espresso测试框架介绍 开源库 AndroidEventBus : 事件总线库V1.0.4版发布,支持Sticky事件:弱引用支持订阅者,无需手动注销. DatePicker : 效果非常好的日历选择器,出自任性的爱哥之手. iOS 领域 技术文章 Swift Core Graphic

197_ViewDragHelper的使用

ViewDragHelper的使用 现在有好多好多应用都用到了抽屉面板 就是滑动的时候 从左侧或者右侧拉出来 然后主界面会变小一点 我们要用到一个API ViewDragHelper,看了一下,父类直接是Object 源码1500行 /** * ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number * of useful operations and state tracking f