Android Best performance Practice (iv)--Layout optimization tips

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/43376527

In the previous articles, we learned how to improve application performance by properly managing memory and high-performance coding techniques. However, in fact, the interface layout will also have a large impact on the performance of the application, if the layout is poorly written, then the program will load the UI is very slow, resulting in a bad user experience. So in this article, let's learn how to provide application performance by optimizing layouts. Friends who have not seen the previous article in front of you suggest that you can read Android Best performance Practice (iii)-high-performance encoding optimization .

reusing layout files

The Android system already offers a lot of handy controls, which makes it easy to write layouts. But there are times when we may need to reuse a well-written layout, and if you are always using copy-and-paste for layout re-use, this is obviously a stupid way to do it. And Android, of course, has taken full account of the importance of layout reuse, so provide <include> and <merge> these two very useful tags, let's learn one by one.

<include>

<include> tags can allow the introduction of another layout in one layout, so for example, all the interface of our program has a common part, this is the best way to extract the public part into a separate layout file, This public layout is then referenced in the layout file for each interface.

Here's an example, we should all know that almost all of the software now has a header layout, the header layout can contain the interface title, Back button, and other operational functions. That kind of a head layout, some software is implemented using Actionbar, but because actionbar flexibility is not very good, so there are many software will choose to write their own implementation. If you do it yourself, because this header layout is used on all interfaces, it's obviously not possible to write the header layout code in every interface, so using the <include> tag in this case is a good fit. To show you this, I'm going to write a very simple header layout, create a new titlebar.xml as the header layout in the Res/layout folder, and the code looks like this:

<?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/back" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layou        T_alignparentleft= "true" android:layout_centervertical= "true" android:text= "Back"/> <textview Android:id= "@+id/title" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" a        Ndroid:layout_centerinparent= "true" android:text= "Title" android:textsize= "20sp"/> <button Android:id= "@+id/done" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Andro Id:layout_alignparentright= "true" android:layout_centervertical= "true" android:text= "Done"/></relativ Elayout>
can see that The layout in Titlebar.xml is very simple, the outer layer is a relativelayout, there are only two buttons and a TextView, the button on the left is used for the return function, the button on the right is used to accomplish the function, the middle TextView can be used to display the current The title of the interface. We can preview what titlebar looks like, as shown in:


OK, that titlebar as a separate layout now we have finished writing, the next work is very simple, regardless of any interface need to join titlebar this function, only need to introduce titlebar.xml in the layout file. So for example our program has a activity_main.xml file, now want to introduce titlebar only need to write this:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <include layout= "@layout/titlebar"/>    ......</linearlayout>
Very simple, a line of include statements can be done. In the <include> tab, you can specify a layout property, which we'll fill in with the name we need to introduce. And using this method of introduction, if the TitleBar interface changes later, we only need to modify the Titlebar.xml this file can be, and not all the interface to modify.

Wait a minute! Now if you run the program will find a big problem, although TitleBar is successfully introduced, but our activity_main.xml in the original interface is all gone! This problem arises because the outermost layout of TitleBar is a relativelayout with a wide height of match_parent, which fills the entire layout, so our original layout is invisible. Since the cause of the problem is clear, I believe you immediately think of how it should be modified, the Layout_height attribute of the relativelayout to Wrap_content can be changed. Yes, it's OK to change this, but this kind of modification will affect all the interfaces that reference titlebar, and how you can use overwrite <include> properties if you just want to have the Activity_main.xml interface affected.

In the <include> tab, we can overwrite all layout properties, that is, the layout property specified in the include overrides the layout property specified in TitleBar. So, here we want to set the height of the titlebar to wrap_content, it can be written like this:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <include        android:layout_width= "match_parent"        android:layout_height= " Wrap_content "        layout=" @layout/titlebar "/>    ......</linearlayout>
Now run the program again and it should be OK, as shown in:


In addition to Layout_height, we can also overwrite any of the layout properties in TitleBar, such as layout_gravity, Layout_margin, etc., instead of the layout property in <include> The label is covered. It is also important to note that if we want to overwrite the layout property in the <include> tag, we have to overwrite both the Layout_width and Layout_height properties, otherwise the overwrite effect will not take effect.

<merge>

The <merge> tag is used as a secondary extension of the <include> tag, and its main purpose is to prevent redundant layout nesting when referencing layout files. As we all know, Android to parse and show a layout is to consume time, the more layout nesting, then the more time to parse, the worse the performance, so we should write the layout file should let the number of nested layers as good as possible.

In the above we explain the use of <include> tag mainly introduces its advantages, but it also has a bad place, is likely to lead to the creation of redundant layout nesting. Here is an example of the way to explain to you, for example, we need to write a public layout to determine the Cancel button, so that any interface needs to identify and cancel the function can not be written separately, new Ok_cancel_layout.xml, the code is as follows:

<?xml    Version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:orientation= "vertical" > <        Button android:id= "@+id/ok" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:layout_marginleft= "20DP" android:layout_marginright= "20DP" android:text= "OK"/> <but         ton android:id= "@+id/cancel" android:layout_width= "match_parent" android:layout_height= "Wrap_content"        android:layout_marginleft= "20DP" android:layout_marginright= "20DP" android:layout_margintop= "10DP" android:text= "Cancel"/></LINEARLAYOUT> 
As can be seen, this interface is also very simple, the outer layer is a vertical direction of the linearlayout,linearlayout contains two buttons, one for the implementation of the deterministic function, one for the implementation of the cancellation function. Now we can preview this interface as shown in:


OK, then we have a profile.xml interface that needs to be edited, so we can introduce the ok_cancel_layout layout into the Profile.xml interface as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >        <edittext        android:id= "@+id/edit"        android:layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:layout_marginbottom= "10DP"        android:layout_marginleft = "20DP"        android:layout_marginright= "20DP"        android:layout_margintop= "10DP"        android:hint= "Edit Something here "/>        <include layout=" @layout/ok_cancel_layout "/></linearlayout>
In Profile.xml, there is a EditText control to edit the content, then use the <include> tag below to introduce the Ok_cancel_layout layout, now rerun the program, the interface effect as shown:


It looks really good, right? However, you are unaware of the situation, the current Profile.xml interface in fact there are already redundant layout nesting! I feel like I haven't written a few lines of code yet, so why is there an extra nesting of layouts? If you don't believe us, we can look at it through the View hierarchy tool, as shown in:


Can see, the outermost layer first is a framelayout, this is understandable, do not know why the outermost is framelayout friend can go to refer to the Android layoutinflater principle Analysis, take you a step in depth understanding view (a) this article. Then the framelayout contains a linearlayout, which is the outermost layout we defined in Profile.xml. The next section is problematic, with two elements in the outermost linearlayout, one edittext and one linearlayout, and then the internal linearlayout contains both the OK and Cancel buttons.

I believe you can see it, this internal linearlayout is a redundant layout nesting, actually do not need such a layer, so that two buttons directly included in the external linearlayout. This extra nesting is caused by the introduction of the layout, because we also define a linearlayout in Ok_cancel_layout.xml. So how do we optimize the problem? Of course, using the <merge> tag to complete, modify the code in the Ok_cancel_layout.xml as follows:

<?xml Version= "1.0" encoding= "Utf-8"? ><merge xmlns:android= "Http://schemas.android.com/apk/res/android" > <        Button android:id= "@+id/ok" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:layout_marginleft= "20DP" android:layout_marginright= "20DP" android:text= "OK"/> <but         ton android:id= "@+id/cancel" android:layout_width= "match_parent" android:layout_height= "Wrap_content"        android:layout_marginleft= "20DP" android:layout_marginright= "20DP" android:layout_margintop= "10DP" android:text= "Cancel"/></MERGE> 
As you can see, here we remove the outermost linearlayout layout of the ok_cancel_layout, swapping the <merge> tags, which means that when there is any place to include this layout, it will <merge> The contents of the tag are populated directly into the include location, and no additional layout structures are added. Good,<merge> usage is so simple, now rerun the program, you will see no changes in the interface, and then we then through the view hierarchy tool to see the current view structure, as shown in:


OK, you can see, now EditText and two buttons are directly included in the linearlayout below, our profile.xml there is no redundant layout nesting.

Load layout only when needed

Sometimes we encounter a scenario where there are a lot of elements in a layout, but not all of the elements are displayed together, but only some of the commonly used elements are shown in ordinary cases, and those that are not used are only displayed if the user is doing something specific.

Here to give a very familiar example, we add the contact person when actually can edit the field really very much, name, telephone, email, fax, address, nickname and so on, but in fact, basically everyone most commonly used is to fill in a name, fill a phone just. So it's not a good idea to show so many complicated fields together on the interface, because most people don't use these fields. The smart thing to do is to display the most commonly used names and phones in the interface, and then give the user an option to add more fields, and when the user really needs to add additional information, we will display the other elements to the interface.

When it comes to implementing such a function, I believe most people's first reaction is to hide the infrequently used elements using invisible or gone and then set them to visible when the user needs to use those elements. This way is sure to achieve functionality, but the performance of the general, because even if the elements are hidden, they are actually in the layout, each element also has its own width, height, background and so on, the resolution of the layout will also be the hidden elements of the one by one parse out.

So how do we get these infrequently used elements to load only when they're needed? Android provides a very lightweight control for this, viewstub. Viewstub Although it is also a view, but it is not size, no drawing function, and does not participate in the layout, the resource consumption is very low, put it in the layout of the basic can be considered to be completely unaffected performance.

Let's learn how to use viewstub to load layouts only when needed. Currently there is only one edittext for editing information in Profile.xml, so for example, we have another three less commonly used edittext that can be defined in another layout file. Create a new Profile_extra.xml file with the code as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <edittext android:id= "@+id/edit_extra1" android:layout_width= "Match_parent" android:layout _height= "Wrap_content" android:layout_marginleft= "20DP" android:layout_marginright= "20DP" Android:hin        t= "Extra field 1"/> <edittext android:id= "@+id/edit_extra2" android:layout_width= "Match_parent"         android:layout_height= "Wrap_content" android:layout_marginleft= "20DP" android:layout_marginright= "20DP" android:layout_margintop= "10DP" android:hint= "Extra field 2"/> <edittext android:id= "@+id/ Edit_extra3 "android:layout_width=" match_parent "android:layout_height=" Wrap_content "Android:layout_ marginleft= "20DP" Android:layout_marginright= "20DP" android:layout_margintop= "10DP" android:hint= "Extra Field 3"/></linearlayout& Gt
As you can see, there are three edittext defined in the Profile_extra.xml layout file, that is, controls that are used to edit infrequently used information, and now we can preview the layout as shown in:


Currently Profile_extra.xml is a standalone layout, and profile.xml This layout file is completely non-related. Next we modify the code in the Profile.xml file as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <edittext android:id= "@+id/edit" android:layout_width= "Match_parent" android:layout_height = "Wrap_content" android:layout_marginbottom= "10DP" android:layout_marginleft= "20DP" Android:layout_ma rginright= "20DP" android:layout_margintop= "10DP" android:hint= "@string/edit_something_here"/> <but        ton android:id= "@+id/more" android:layout_width= "wrap_content" android:layout_height= "Wrap_content"        Android:layout_gravity= "Right" android:layout_marginright= "20DP" android:layout_marginbottom= "10DP" android:text= "More"/> <viewstub android:id= "@+id/view_stub" android:layout= "@layout/prof Ile_extra "Android:layout_wiDth= "Match_parent" android:layout_height= "wrap_content"/> <include layout= "@layout/ok_cancel_layou T "/></linearlayout>
As you can see, here we have added a more button, which is used to load the elements that are not commonly used, and then defines a viewstub below the button. In the Viewstub control, we gave it a unique identity through the id attribute, passed the layout property to the Profile_extra, and then gave Viewstub a wide height. Note that although Viewstub does not occupy any space, each layout must specify the Layout_width and Layout_height properties, or the operation will cause an error.

Then modify the code in the Profileactivity, add the Click event of the More button in the activity, and do the following logic processing in the Click event:

Private EditText editextra1;private EditText editextra2;private EditText editextra3;public void Onmoreclick () {viewstub Viewstub = (viewstub) Findviewbyid (r.id.view_stub); if (viewstub! = null) {View Inflatedview = Viewstub.inflate (); EditExtra1 = (EditText) Inflatedview.findviewbyid (R.ID.EDIT_EXTRA1); editExtra2 = (EditText) Inflatedview.findviewbyid (R.ID.EDIT_EXTRA2); editExtra3 = (EditText) Inflatedview.findviewbyid (R.ID.EDIT_EXTRA3);}}
When we click on the more button we will first call the Findviewbyid () method to get the instance of Viewstub, it is very simple to get the Viewstub instance, call the inflate () method or setvisibility ( view.visible) can load the hidden layout, and the layout that is loaded is the Profile_extra layout that you just configured in XML.

After calling the inflate () method, the loaded layout is returned, and then we can manipulate the layout arbitrarily, hide the display again, or get an instance of the child element. Notice here that I have a non-null judgment on the Viewstub instance because the ID defined in the XML is only valid at first, and once the layout specified in the viewstub is loaded, the ID fails, then Findviewbyid () The resulting value will also be empty.

Now let's run the program again, as shown in the interface:


As you can see, there is only one more button on the interface, and Viewstub does not occupy any space at all. Then click the More button and the new interface looks like this:


No problem, the layout defined in Profile_extra.xml has already been loaded, and the location shown is between the more button and the OK button, exactly where the viewstub control is defined, stating that we have actually successfully used the viewstub.

Also need to remind everyone, viewstub loading layout is not allowed to use <merge> tags, so this may lead to the layout of the load out there are redundant nesting structure, how to choose the actual situation according to their own decision, For those situations where the hidden layout file structure is quite complex, the use of viewstub is still a pretty good choice, even if a layer of useless layout is added, the benefits outweigh the disadvantages.

After four articles of study, we have mastered a lot of skills to improve the performance of Android applications, most of which are from the Android Doc, I also choose some of the more useful parts of the feeling, and then add their own understanding presented to everyone. If you want to continue to learn more about performance optimization techniques, you can read more http://developer.android.com/training/best-performance.html on this website.

Well, that's the end of the article on the Best Performance Practice series, thank you for your patience to see the last.

First time to get blog update reminders, as well as more technical information sharing, welcome to follow my public number, sweep the QR code below or search number Guolin_blog, you can pay attention to.

Android Best performance Practice (iv)--Layout optimization tips

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.