Tags
android, custom view, custom viewgroup, custom-ui, imageblock, layout, linearlayout, measureChild, MeasureSpec, onMeasure, optimize, relativelayout, viewgroup
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?
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!
Thanks. This is awesome analysis.
Can you provide the code that how you log the measure info? It seems very useful ๐
I used a CustomLinearLayout, CustomTextView, CustomImageView, etc with overriden onMeasure(). You can also use Probe library for logging.
Cool…, Thanks
I realize it accord to the article. Welcome to download and point the defectใ https://github.com/huanting/Performance_CustomViewGroup
I ran into an interesting “custom” ViewGroup implementation in the email app awhile back. i.e. They actually use the built in layout code, but they cache all of the layout the first time it happens (see http://androidxref.com/4.4.4_r1/xref/packages/apps/UnifiedEmail/src/com/android/mail/browse/ConversationItemView.java#733 and http://androidxref.com/4.4.4_r1/xref/packages/apps/UnifiedEmail/src/com/android/mail/browse/ConversationItemViewCoordinates.java). Subsequent rows just load the cached data and use that. i.e. There’s still a custom onDraw method (its not a real ViewGroup), but changing the layout is just changing the xml. Good when you just want to stamp the exact (and I mean exact, regardless of the message) same layout over and over and over.
Is it also possible to use GridLayout here? If so, how well will it perform?
May be yes. You could try it with GridLayout. I am certain that I will not work better the custom ViewGroup.
You forgot to set the orientation of the first LinearLayout
By default it’s horizontal. So you don’t have to set it.
Just a few remarks:
1. I think it would be nice to mention that the third measurement pass happens because of layout_weight. If we remove it and set layout_width=”wrap_content”, we won’t get desired layout, but vertical linear layout would be measured only once.
2. “These are expensive operations as Layouts are created and thrown away during the second pass.” Sorry, didn’t get that part. Which layouts are thrown away?
3. “The Title and Subtitle are always to the left of the ProfilePhoto and the right of the Menu button.” The Title and Subtitle are always to the RIGHT of the ProfilePhoto and the LEFT of the Menu button.
Thx,
Alex
1. What’s the point in setting it to “wrap_content” if we won’t get the desired layout? ๐
2. I meant text Layouts there. When TextView’s are measured they create (Static/Boring)Layouts. But during the next measure pass, they are thrown away (unless it’s BoringLayout with same Metrics).
3. Oops. Will fix it. Thanks.
Hi Sriram,
thank you for your answers.
1. My initial intent was to emphasize that the third measurement pass happens not “just because”, but due to layout_weight attribute.
2. Got it, thx.
Regards,
Alex
The way I have set up my layout, that’s the most optimized way to use “layout_weight”.
Nice writeup, albeit complicated to wrap one’s head around. My question is, why don’t I see examples like this in the Android SDK samples directory? If Google was serious about having devs optimize their layouts, then they surely would’ve advocated this approach.
“This approach has proven to be effective” – Can you provide any ‘measure’ for it? ๐
We use this in Facebook for Android app extensively. The events dashboard uses this layout and had a 100ms win in startup time. 100ms for 6 rows is a huge deal! ๐ You can write your own benchmarks to see if they are valid or not ๐
Maybe your problem was the way you were fetching data to show in this layout. Perhaps you aren’t using RXJava, and doing some silly IntentService or Handler threads, which wouldn’t be as streamlined at doing network calls asynchronously and updating the UI. Maybe it isn’t the layouts that were causing your lags. Just a thought…
It doesn’t matter how I fetch the data and where the data comes from or how much latency is there on the network.
This is just a better optimization for Views with static information.
Pingback: ViewInspector ไธไธช Android ๅผๅ็ UI ่ฐ่ฏๅฉๅจ - Calmๅๅฎข
Pingback: ViewInspector | ๅ ญ็ ็ฝ
Pingback: Custom ViewGroups – Linktail
you mentioned in relativelayout, child with no constraint measure first ..but what i get in log is opposite
log syntax – [TAG] : w- MeasureSpec.toString(measureHeightSpec) : h- MeasureSpec.toString(measureWidthSpec)
[b] : w-MeasureSpec: AT_MOST 480 : h-MeasureSpec: AT_MOST 672
[a] : w-MeasureSpec: AT_MOST 480 : h-MeasureSpec: AT_MOST 672
[a] : w-MeasureSpec: EXACTLY 0 : h-MeasureSpec: AT_MOST 672
[b] : w-MeasureSpec: EXACTLY 0 : h-MeasureSpec: AT_MOST 643
[b] : w-MeasureSpec: AT_MOST 480 : h-MeasureSpec: AT_MOST 744
[a] : w-MeasureSpec: AT_MOST 480 : h-MeasureSpec: AT_MOST 744
[a] : w-MeasureSpec: EXACTLY 0 : h-MeasureSpec: AT_MOST 744
[b] : w-MeasureSpec: EXACTLY 0 : h-MeasureSpec: AT_MOST 715
[b] : w-MeasureSpec: AT_MOST 480 : h-MeasureSpec: AT_MOST 744
[a] : w-MeasureSpec: AT_MOST 480 : h-MeasureSpec: AT_MOST 744
[a] : w-MeasureSpec: EXACTLY 0 : h-MeasureSpec: AT_MOST 744
[b] : w-MeasureSpec: EXACTLY 0 : h-MeasureSpec: AT_MOST 715
thanks in advance
Can you please provide the full code