原文地址:https://sriramramani.wordpress.com/2015/05/06/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.

                                            <Subtitle                android:layout_width="match_parent"                android:layout_height="wrap_content"/>        </LinearLayout>        <Menu            android:layout_width="20dp"            android:layout_height="20dp"/>    </LinearLayout></pre>   <p>And the measure pass happens as follows on a Nexus 5.</p>   <pre><code class="language-plain">    > 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    ]</code></pre>   <p>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.</p>   <p>Does a RelativeLayout work better here?</p>   <pre class="brush: xml; title: ; notranslate">    <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></pre>   <p>And the measure pass looks like this.</p>   <pre><code class="language-plain">    > 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]</code></pre>   <p>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.</p>   <p>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.</p>   <pre><code class="language-java">    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);        }    }</code></pre>   <p>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, <code>measureChildWithMargins()</code> 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, <code>makeMeasureSpec()</code>, 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.</p>   <pre><code class="language-plain">    > 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]</code></pre>   <p>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 <code>onLayout()</code> as an exercise for the reader <span class="wp-smiley wp-emoji wp-emoji-wink"> ;)</span></p>
<p align="center" class="pageLink"></p>
<div id="wen"></div>
<!--<div style="height: 280px;">ads</div>-->

<h2><a href="/R/8Bz8WG6Ldx/">更多相关文章</a></h2>	
<ol>
<li><a href="/android/ki69e.html" title="Android(安卓)开源项目分类汇总">Android(安卓)开源项目分类汇总</a></li><li><a href="/android/ki687.html" title="Android(安卓)网页加载完成ProgressDialog运用">Android(安卓)网页加载完成ProgressDialog运用</a></li><li><a href="/android/ki685.html" title="Android(安卓)获取ip地址">Android(安卓)获取ip地址</a></li><li><a href="/android/ki67z.html" title="Android(安卓)Power Management【by Steve Guo】">Android(安卓)Power Management【by Steve Guo】</a></li><li><a href="/android/ki67r.html" title="Appcelerator Cloud Push Notification in Android">Appcelerator Cloud Push Notification in Android</a></li><li><a href="/android/ki666.html" title="Appcelerator Cloud Push Notification in Android">Appcelerator Cloud Push Notification in Android</a></li><li><a href="/android/ki66p.html" title="Android系统版本和API等级(level)对照表">Android系统版本和API等级(level)对照表</a></li><li><a href="/android/ki64d.html" title="Android(安卓)Studio 1.0正式稳定版下载地址">Android(安卓)Studio 1.0正式稳定版下载地址</a></li><li><a href="/android/ki633.html" title="LowMemoryKiller in Android">LowMemoryKiller in Android</a></li></ol>

<h2>随机推荐</h2>	
<ol>
<li>
<a href="/android/bcd3b.html" title='Android架构分析之JNI' target="_blank">Android架构分析之JNI</a></li>
<li>
<a href="/android/bcd3c.html" title='文件操作与SDCard读写访问' target="_blank">文件操作与SDCard读写访问</a></li>
<li>
<a href="/android/bcd3d.html" title='android Fragment添加Theme,使背景模糊' target="_blank">android Fragment添加Theme,使背景模糊</a></li>
<li>
<a href="/android/bcd3e.html" title='Android framework初识' target="_blank">Android framework初识</a></li>
<li>
<a href="/android/bcd3f.html" title='多个控件跑马灯效果' target="_blank">多个控件跑马灯效果</a></li>
<li>
<a href="/android/bcd3g.html" title='android播放音频文件(MediaPlayer)和录音(MediaRecorder)--播放音频文件' target="_blank">android播放音频文件(MediaPlayer)和录音</a></li>
<li>
<a href="/android/bcd3h.html" title='Android 兼容性测试(CTS)' target="_blank">Android 兼容性测试(CTS)</a></li>
<li>
<a href="/android/bcd3i.html" title='Android优化和性能' target="_blank">Android优化和性能</a></li>
<li>
<a href="/android/bcd3j.html" title='Android进程回收' target="_blank">Android进程回收</a></li>
<li>
<a href="/android/bcd3k.html" title='eclipse中Android布局的基本操作' target="_blank">eclipse中Android布局的基本操作</a></li>
</ol>
</div>
<div class="next-prev-posts clearfix">
</div>

</div>

<div class="clear"></div>

</div>	

<!--<div class="widget"><h3><span>热门专题</span></h3>
<div class="widge_tags">
<div class="tag-items" style="float: left;">
<a href="/" title=""></a>
</div>

</div>
</div>-->

</div>
</div>
</div>

<div class="clearfix"></div>
<div id="footer" class="two-s-footer">
<div class="footer-box">
<div class="container">
<div class="row" style="padding-left: 15px;padding-right: 15px;">
<div class="nav-footer">
<a href="/">Home</a>
</div>
<div class="copyright-footer">
<p>Powered By 16lz.com</p>

</div>
</div>
</div>
</div>
</div>

<div style="display:none">
<script charset="UTF-8" id="LA_COLLECT" src="//sdk.51.la/js-sdk-pro.min.js"></script>
<script>LA.init({id: "1x5g7IvCFerRo43g",ck: "1x5g7IvCFerRo43g"})</script>
</div>
<script src="/theme/szd/js/echo.js"></script>
<script src="/theme/szd/js/bestai_code.js"></script>

</body>
</html>