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!

转载于:https://my.oschina.net/jerikc/blog/494906

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值