Android Layout Optimization

Source: Internet
Author: User

Android Layout Optimization
Preface

This article is the layout of Android optimization. This part should be very important in Android, whether in custom controls or in simple writing layout, we should try to follow some optimization principles so that the layout can be more efficient and the experience can be better.

1. Optimize the layout hierarchy

If the Layout structure is too complex, the rendering process of Android will be complicated and the measure process will be complicated. The View rendering mechanism I analyzed details the entire measurement, Layout, and drawing process, too complex and nested la S may cause performance problems.

1.1 avoid nesting

Nested LinearLayout may make the hierarchical structure of the View very deep. When using LinearLayout, we usually like to use nested layout to dynamically set the Visibility of a View. Because LinearLayout is linear, even hiding a View will not affect the arrangement of other views. In RelativeLayout, the bitwise of the View is relative to other views. Therefore, after hiding it, the previous View does not have a reference object, resulting in a relative location change, in this case, you can use alignWithParentIfMissing = "true" to handle this situation.

In addition, nested LinearLayout with the layout_weight parameter requires a particularly large amount of computing, because each child element needs to be measured twice. This is especially important for Layout that requires repeated inflate times, such as when ListView or GridView is used.

1.2 use the merge tag to optimize the hierarchy

When include is used, too many layout nesting and unnecessary layout nodes may occur, resulting in slow resolution.

The merge tag can be used in two typical scenarios:

  • The layout top node is FrameLayout and does not need to set attributes such as background or padding. You can use merge instead, because the parent view tried by the Activity content is a FrameLayout, so you can use merge to eliminate only one.

  • When a layout is included by other la s as a sub-layout, merge is used as the top node of the layout. As a result, the top node is automatically ignored when it is introduced, merge all its subnodes into the main layout.

    For example, if you have a Layout that is a vertical LinearLayout with two consecutive views that can be reused in other Layout, you will create a LinearLayout that contains the two views, for reuse. However, when another LinearLayout is used to nest this reusable LinearLayout, this nested LinearLayout method has no significance in addition to slowing down your UI performance.

    To avoid this situation, you can use elements to replace the reusable Layout root node. For example:

    12345678910 "http://schemas.android.com/apk/res/android" > android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "@string/add" /> android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "@string/delete" />

    Now, when you want to include this Layout to another Layout (and use tags), the system will directly put the two buttons in Layout, without any redundant Layout being nested.

    2. Use tags to reuse Layout

    If your program UI repeatedly uses a Layout in different places, this section teaches you how to create efficient and reusable Layout components and "include" them into the UI Layout.

    To efficiently reuse the entire Layout, you can use and tag to embed other Layout into the current Layout.

    3. Load view on demand

    In addition to simply including one Layout to another, you may also want to start loading only when your Layout is visible to users after the program starts.

    3.1 Layout that does not need to be loaded immediately. If it is set to GONE, the system will skip this step. If it does not load 3.2, ViewStub will be used for on-demand loading.

    ViewStub is a lightweight view that does not require size information or draw anything in the added Layout. For each ViewStub, you only need to set the android: layout attribute to specify the Layout type to be inflate. Viewstub is often used to introduce the la s that are not displayed by default and only displayed under special circumstances, such as the progress layout, the refreshing layout displayed when the network fails, and the layout prompts when information errors occur.

    The following ViewStub is a translucent progress bar covering layer. In terms of function, it should be visible only when new data items are imported to the application.

    1234567 android:id= "@+id/stub_import" android:inflatedId= "@+id/panel_import" android:layout= "@layout/progress_overlay" android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:layout_gravity= "bottom" />

    Load ViewStub
    When you want to load the Layout declared by ViewStub, either set its visibility using setVisibility (View. VISIBLE) or call its inflate () method.

    The following uses network_error.xml as an example when a network error is added to the layout main. xml. The main. mxl code is as follows:

    1234567891011 "1.0" encoding="utf-8"?> "http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "match_parent" > …… android:id= "@+id/network_error_layout" android:layout_width= "match_parent" android:layout_height= "match_parent" android:layout= "@layout/network_error" />

    Network_error.xml indicates the layout that must be displayed only when a network error occurs.

    SetVisibility (View. VISIBLE) Method

    123 View viewStub = ((ViewStub)findViewById(R.id.stub_import));viewStub.setVisibility(View.VISIBLE);netErrorLayout = findViewById(R.id.net_error_layout))

    Inflate Method

    1 View netErrorLayout = ((ViewStub) findViewById(R.id.net_error_layout)).inflate();

    Note:
    The inflate () method is returned to the inflate view after the rendering is complete. Therefore, you do not need to call findViewById () to find this element. Reducing the number of inflate operations also improves efficiency.
    The setVisible method also needs to find the elements in ViewStub by findViewById again.

    Once ViewStub is visible or inflate, The ViewStub element does not exist. Replaced by Layout of inflate, whose id is the android: inflatedId attribute on ViewStub. (The android: id attribute of ViewStub is only available before ViewStub is visible)

    Note: One drawback of ViewStub is that it currently does not support the use of tag Layout.

    Iv. ListView Optimization

    If you have a ListView that contains complex items or that each item contains a lot of data, the performance of up/down scrolling may be reduced. This section provides some tips on how to make scrolling smoother.
    The key to program smoothness is to prevent the main thread (UI thread) from performing a large number of operations. Make sure that you perform disk read/write, network read/write, or SQL operations in other threads. To test the status of your application, you can enable StrictMode.

    4.1 Use background threads

    You should extract time-consuming operations in the main thread to a background thread so that the winner thread only pays attention to UI painting.

    4.2 fill in View objects in View Holder

    Use convertView,
    Your code may often use findViewById () when the ListView slides, which will reduce the performance. Even if the Adapter returns a convertView for recycling, you still need to search for this element and update it. One of the methods to avoid frequent calls to findViewById () is to use the View Holder (View placeholder) design mode.

    ViewHolder stores each view under the tag. In this way, you do not need to frequently search for this element:

    1234567 static class ViewHolder { TextView text; TextView timestamp; ImageView icon; ProgressBar progress; int position;}

    Then, a ViewHolder object is generated in the Layout class:

    1234 ViewHolder holder = new ViewHolder();holder.icon = (ImageView) convertView.findViewById(R.id.listitem_image);...convertView.setTag(holder);

    In this way, you can easily obtain each view, instead of using findViewById () to constantly search for the view, saving valuable computing time.

    4.3 getView do not perform complex operations

    Because getView is called every time an Item is moved into the screen, do not perform complicated operations in getView, and do not frequently create objects. Do not process Item clicks in advance. GetView is called frequently, especially during fast sliding.

    5. Optimization tips

    Try RelativeLayout to reduce hierarchy nesting.
    Use the layout_weight attribute of LinearLayout with caution. Use centerHorizontal = "true", toLeft, and toRight of RelativeLayout instead.

    6. Optimize the naming of 6.1 IDs in writing specifications

    To facilitate identification, you can name the resources on the current interface based on your business. For example, if you are currently logged on to the interface, you can name it as follows:
    Login_edit_username
    Login_edit_password
    Login_btn_submit
    Login_txv_forgot_pass

    6.2 Resource naming

    Ic_action_add, ic_action_location (ActionBar Icons)
    Ic_play, ic_save (General Icons)
    Ic_tab_music, ic_tab_more (Tab Icons)

    6.3 general resource naming

    For style. xml and dimens. xml Naming can be generic as much as possible, because many basic views of a project are generic, such as ActionBar and ListView. Standardized and general naming can be easily transplanted to other projects.

    12345678910 "list_item_large" > #FCA558 "list_item_small" > #FBA228 "list_item_large" >24dp "list_item_small" >18dp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.