Performance optimization of Android layout optimization

View of the measurement system in Android, when layout and drawing, operations are performed by traversing the tree of View. If a tree's height is too high View will seriously affect the measurement, layout and speed of the draw. Google is also its API documentation View recommended height should not exceed 10 layers.

Optimization ideas

Android layout affect the essence of the performance is the impact of the page 测量and 绘制time.

Page and a completion of the measurement process by the recursive drawing, i.e. measure, layoutprocess.

It can be optimized from the following aspects to improve page display speed Android applications:

  • Select the appropriate layout type
  • Reduce the level layout
  • Improve the layout of reusability
  • Draw reduce measurement time

Optimization

Select the appropriate layout type

By selecting the type of a reasonable layout, thereby reducing nesting and improves the performance of the layout.

Namely: Upon completion of the complex effect UI, select functions as a complex layout (eg: RelativeLayout, ConstraintLayout) to complete, instead of to the simple layout of a plurality of functions (eg: FrameLayout, LinearLayout) nested completed.

Improve performance is to choose a layout takes performance (CPU resources and time) less layout.

  • Low cost performance layout: simple function (such as: FrameLayout, LinearLayout)
  • High cost performance layout: complex functions (eg: RelativeLayout, ConstraintLayout)

Before about Android 4.0, the default layout of the new construction is in the root LinearLayout, and after it has been changed RelativeLayout, because RelativeLayoutbetter performance, and can achieve a simple LinearLayoutlayout of nesting can be achieved. 2017 Google released the official version of Android Studio 2.3, the new version of the Android Studio 2.3 project layout is the default root ConstraintLayout, because ConstraintLayoutperformance than RelativeLayoutbetter.

As little as possible wrap_content

Layout properties wrap_contentcalculation time would increase the cost of the layout of the measurement, should be as little as possible. In the known width and height of a fixed value is not used in wrap_contentproperty.

Use Layout tab

<Include> tag

<include> Tags are often used to extract the public part of the layout out for other common layout, in order to achieve a modular layout, easy to write this provides much convenience in the layout.

In a layout below to main.xml by includeintroducing another layout Example foot.xml. main.mxl code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/simple_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="@dimen/dp_80" />

    <include layout="@layout/foot.xml" />

</RelativeLayout>

Wherein includefoot.xml incorporated common bottom page, as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_40"
        android:layout_above="@+id/text"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_40"
        android:layout_alignParentBottom="true"
        android:text="@string/app_name" />

</RelativeLayout>

<include>The only property is the tag layoutattribute specifies the layout of the document needs to include. It can be defined android:idand android:layout_*properties to cover the corresponding attribute value of the root node is introduced into the layout. Note redefined android:id, the top node of the sub-layout idon the change.

<Viewstub> tag

<viewstub>Label with includesame label can be used to introduce an external layout, except that the viewstublayout of the default introduced not expand, i.e. neither displayed nor occupied positions occupied, thereby saving CPU memory and parsing the layout. <viewstub>Tags used to introduce those defaults are not displayed, refresh layout layout displayed only in exceptional circumstances, such as progress layout, display of network failure, an error message appears prompt layout.

The following pages when prompted to join the network in a layout error main.xml in network_error.xml example. main.mxl code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    ……

    <ViewStub
        android:id="@+id/network_error_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout="@layout/network_error" />

</RelativeLayout>

Which viewstubnetwork_error.xml was introduced only in the network error large columns  to optimize the performance of Android layout optimization layout if you want to display, default will not be resolved, the sample code as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/network_setting"
        android:layout_width="@dimen/dp_160"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/network_setting" />

    <Button
        android:id="@+id/network_refresh"
        android:layout_width="@dimen/dp_160"
        android:layout_height="wrap_content"
        android:layout_below="@+id/network_setting"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/dp_10"
        android:text="@string/network_refresh" />

</RelativeLayout>

By in Java ViewStub viewStub = findViewById(id)found ViewStubonly when a ViewStub the inflate()method is invoked, or is set to visible, this ViewStubpoints to the layout of the document will be loaded, and replace the current ViewStubposition. Therefore, ViewStub exists in the view hierarchy until setVisibility(int)or inflate()method is called, otherwise it is not to load the control, so small consumption of resources. Usually call it "lazy include".

Note: For one ViewStub, when setVisibility(int)or inflate()after the method is called, this ViewStubis specified in the layout Viewreplacement, so been called inflate()methods ViewStub, if you want to display again after being hidden, you can not use the inflate()method, but can be used again setVisibility(int)method is set to visible, which is the difference between these two methods.

<Merge> tag

In using includethe nested arrangement may result in excessive, unnecessary extra layout nodes, resulting in slow parsing, and unnecessary nodes by nested hierarchy vieweror 设置->开发者选项->显示布局边界view.

<merge> Tags can be used in two typical cases:

  • Is a top layout nodes FrameLayoutand need not be provided background, or paddingthe like properties, may be mergereplaced, because Activitythe root node is a FrameLayout, it is possible to use mergeonly one elimination.
  • As the sub layout is a layout of the other layout includewhen used mergeas the root node of the layout, the root node are automatically ignored when introduced into, and fully incorporated into the main layout of its child nodes.

<merge>Only use as the root tag of the XML layout. When Inflate to <merge>at the beginning of the layout of the document, you must specify a parent ViewGroup, and must be set attachToRootto true.

to sum up

label Features description
<include> Improve the layout of reusability Extracting a common portion between the layout, by increasing the reusability thereby reducing the layout drawing time measurement
<viewstub> Draw reduce measurement time Drawing to reduce measurement time, the layout can directly improve the performance of
<merge> Reduce the level layout Level reduction layout, direct measurement of reduced drawing time, to improve the performance of layout

Other optimization

Common View SurfaceView or replaced with TextureView

SurfaceViewOr TextureViewyou can improve performance by drawing operation moved to another separate thread. View of ordinary drawing process is done in the main thread (UI thread), if some drawing operations affect the performance of optimized bad, then you can consider the use SurfaceViewand TextureViewthe other, their drawing operations occur outside the UI thread on the thread.

Because SurfaceViewin addition to the conventional view of the system, it is not the same as a conventional attempt to move, scale or rotate a SurfaceView. TextureViewAndroid 4.0 is introduced, and in addition SurfaceViewas a separate thread in the drawing, but may also be the same as the conventional view is changed.

Use RenderJavascript

RenderScript Adnroid 3.0 is the introduction of a language used to write high performance code on Android, grammar give the C99 standard C language, his structure is independent, there is no need for different CPU or GPU custom code.

Use OpenGL drawing

Android supports the use of OpenGLhigh-performance graphics API, which is available for Android the most advanced graphics mechanism, in-game high of applications widely used performance requirements.

Android 4.3 The biggest change is support OpenGL ES 3.0. Compared to 2.0 and 3.0 have more buffer objects, adds a new shading language, increasing the multi-texture support, and so on, will bring better visual experience Android game.

Layout tuning tools

Hierarchy Viewer

Hierarchy ViewerAndroid Studio is provided UI performance testing tool. Visualization can help developers get UI layout structure and properties of a variety of information to help optimize the layout design. Hierarchy Viewer Activity can easily view the layout, each View properties, measured and drawn layout time. Specific description visible Hierarchy Viewer

Android Studio version 3.1 or later, Hierarchy Viewer has been abandoned, it is recommended to use at run time Layout Inspectorto check the application process view hierarchy.

Layout Inspector

Layout InspectorAndroid Studio is a new alternative to the Hierarchy Viewer program. Android Studio using the layout checker can check its own view hierarchy of the application from the IDE Android Studio at runtime. If the layout at runtime (and not entirely in XML) building and the layout does not appear as expected, this check will be very useful. Specific introduced seen Layout Inspector

Follow these steps to open the layout inspector:

  • Run your application on a device or emulator.
  • Click Tools> Android> Layout Inspector.
  • Choose Process in the dialog box that appears, select the application process you want to check, and then click OK.

Lint

LintCode scan analysis is a tool provided by Android Studio, you can scan and found the code structure and quality problems and provide solutions. Lint each problem has found a description and rating (tested and found very similar bug), it can easily locate and fix problems according to severity. Specific description visible Lint

systrace

SystraceAndroid 4.1 is the new performance data sampling and analysis tool. It helps the developer to collect Android critical subsystems (e.g. Surfaceflinger, WindowManagerService framework and other portions of the key modules, services) operating information to help analyze more intuitive developer system bottlenecks, improve performance. Specific description visible Systrace

Systrace features include I / O operations, the kernel work queue, CPU load and other operating conditions of the various subsystems Android tracking system. In the Android platform, which is mainly composed of three parts:

  • Core part: Systrace advantage ftrace function in Linux Kernel. So if you want to use Systrace must be turned on in the kernel module and associated ftrace.
  • Data acquisition: Android Trace defines a class. The application process can be output to ftrace use of such statistics. Meanwhile, Android atrace there is a process, it can read the statistics from ftrace and then to the data analysis tools to deal with.
  • Data analysis tools: Android provides a systrace.py (Python pace of documents, Android SDK is located in the directory / tools / systrace, it will call atrace internal process) is used to configure the way data acquisition (such as data collection tags, document name output etc.) and ftrace collect statistical data and generates a results page for users to view documents.

Essentially, Systrace is in Linux Kernel ftrace package, the application process need to use the Trace class provided by Android to use Systrace.

Guess you like

Origin www.cnblogs.com/liuzhongrong/p/11986273.html