android custom viewgroups 性能分析

本文深入探讨了在复杂UI中优化Android布局性能的方法,通过创建自定义ViewGroup来减少视图测量过程,提高应用表现。具体案例展示了如何通过手动计算布局尺寸,避免不必要的测量操作,从而实现更高效的布局管理。

原文地址: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.

    <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 ;)

【Koopman】遍历论、动态模态分解和库普曼算子谱特性的计算研究(Matlab代码实现)内容概要:本文围绕【Koopman】遍历论、动态模态分解和库普曼算子谱特性的计算研究展开,重点介绍基于Matlab的代码实现方法。文章系统阐述了遍历理论的基本概念、动态模态分解(DMD)的数学原理及其与库普曼算子谱特性之间的内在联系,展示了如何通过数值计算手段分析非线性动力系统的演化行为。文中提供了完整的Matlab代码示例,涵盖数据驱动的模态分解、谱分析及可视化过程,帮助读者理解并复现相关算法。同时,文档还列举了多个相关的科研方向和技术应用场景,体现出该方法在复杂系统建模与分析中的广泛适用性。; 适合人群:具备一定动力系统、线性代数与数值分析基础,熟悉Matlab编程,从事控制理论、流体力学、信号处理或数据驱动建模等领域研究的研究生、博士生及科研人员。; 使用场景及目标:①深入理解库普曼算子理论及其在非线性系统分析中的应用;②掌握动态模态分解(DMD)算法的实现与优化;③应用于流体动力学、气候建模、生物系统、电力系统等领域的时空模态提取与预测;④支撑高水平论文复现与科研项目开发。; 阅读建议:建议读者结合Matlab代码逐段调试运行,对照理论推导加深理解;推荐参考文中提及的相关研究方向拓展应用场景;鼓励在实际数据上验证算法性能,并尝试改进与扩展算法功能。
本系统采用微信小程序作为前端交互界面,结合Spring Boot与Vue.js框架实现后端服务及管理后台的构建,形成一套完整的电子商务解决方案。该系统架构支持单一商户独立运营,亦兼容多商户入驻的平台模式,具备高度的灵活性与扩展性。 在技术实现上,后端以Java语言为核心,依托Spring Boot框架提供稳定的业务逻辑处理与数据接口服务;管理后台采用Vue.js进行开发,实现了直观高效的操作界面;前端微信小程序则为用户提供了便捷的移动端购物体验。整套系统各模块间紧密协作,功能链路完整闭环,已通过严格测试与优化,符合商业应用的标准要求。 系统设计注重业务场景的全面覆盖,不仅包含商品展示、交易流程、订单处理等核心电商功能,还集成了会员管理、营销工具、数据统计等辅助模块,能够满足不同规模商户的日常运营需求。其多店铺支持机制允许平台方对入驻商户进行统一管理,同时保障各店铺在品牌展示、商品销售及客户服务方面的独立运作空间。 该解决方案强调代码结构的规范性与可维护性,遵循企业级开发标准,确保了系统的长期稳定运行与后续功能迭代的可行性。整体而言,这是一套技术选型成熟、架构清晰、功能完备且可直接投入商用的电商平台系统。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值