In-depth analysis of Android custom layout and android custom Layout

Source: Internet
Author: User

In-depth analysis of Android custom layout and android custom Layout

Link: http://greenrobot.me/devpost/android-custom-layout/

Preface:

This article is written by Lucas Rocha, a former Firefox Android Engineer (now switching to Facebook). It provides a good analysis of the four custom layout schemes commonly used in Android, combined with the sample projects written by the four Android custom layout schemes, this article describes their respective advantages and disadvantages and the comparison between the four schemes. After reading this article, I also have a better understanding of the Android custom layout. So I started to translate it into Chinese, and the original article is linked here.

 

As long as you have written the Android program, you must have used several built-in la s on the Android platform --RelativeLayout,LinearLayout,FrameLayoutAnd so on. They can help us build a good Android UI.

These built-in la s provide many convenient components, but in many cases you still need to customize your own la S.

To sum up, the custom layout has two advantages:

  1. By reducing the use of views and faster traversal of layout elements, you can make your UI display more efficient;
  2. You can build UIs that cannot be implemented by existing views.

In this blog post, I will implement four different custom la S and compare their advantages and disadvantages. They are composite view, custom composite view, flat custom view, and async custom views.

These code implementations can be found in the android-layout-samples project on my github. This app uses the four custom la s mentioned above to achieve the same UI effect. They use Picasso to load images. The UI of this app is only a simplified version of twitter timeline-no interaction, only layout.

Well, let's start with the most common custom Layout:Composite view.

Composite View

Composite views(Also known as compound views) is the easiest way to combine multiple views into a reusable UI component. The implementation process of this method is as follows:

  1. Inherit related built-in la S.
  2. Fill inMergeLayout.
  3. Initialize member variables and passFindViewById ()Point to internal view.
  4. Add a custom API to query and update the view status.

TweetCompositeViewCode is a composite view. It inherits fromRelativeLayoutAnd filledTweet_composite_layout.xmlCode layout file, and finally exposed to the outside worldUpdate ()Method to update its status in adaptercode.

Custom Composite View

As mentioned aboveTweetCompositeViewThis implementation method can meet most situations. However, in some cases, it will not work. Suppose you want to reduce the number of child views to make the convenience of layout elements more effective.

At this time, we can look back and see that although the implementation of composite views is relatively simple, there is still a lot of overhead to use these built-in la S-especiallyLinearLayoutAndRelativeLayoutThis is a complicated container. Because of the built-in layout Implementation of the Android platform, in a layout element traversal, the system needs to process the combination of many la S and multiple measurements of sub-Views --LinearLayoutOfLayout_weightIs a common example.

Therefore, you can customize a set of sub-view computing and positioning logic for your app, so that you can greatly optimize your UI. This is what I will introduce next.Custom composite view.

As the name implies, a custom composite view is a rewriting.OnMeasure ()AndOnLayout ()The composite view of the method. Therefore, compared with the previous composite viewRelativeLayout,Now we need to go further -- inherit more abstractViewGroup.

TweetLayoutViewCode is implemented through this technology. Note that the current implementation is notTweetComposiveViewInheritedLinearLayoutThis avoidsLayout_weightCode is used.

This large cost-effective process is achieved through ViewGroup'sMeasureChildWithMargins ()Methods andGetChildMeasureSpec ()Method to CalculateMeasureSpec.

TweetLayoutViewIt cannot process all possible layout combinations correctly, but it does not have. We certainly need to optimize our custom layout based on specific needs. This method allows us to write simple and efficient layout code.

Flat Custom View

As you can see, custom composite views can be simply usedViewGroupThe API can be implemented. Most of the time, this implementation can meet our needs.

However, if we want to go further-optimize the UI of the key parts of our application, suchListViews,ViewPagerAnd so on. If we put allTweetLayoutViewWhat if the sub-view is merged into a single custom view and then managed in a unified manner? This is what we will discuss next.Flat custom view-- See the image below.


Custom composite view on the left and flat custom view on the right

 

Flat custom view is a fully customized view. It is fully responsible for the calculation, location arrangement, and drawing of internal subviews. So it inheritsViewInsteadViewGroup.

If you want to find out whether an app exists in real life, it is very simple-enable the "display layout boundary" option in "Developer mode" on your mobile phone, and then open Twitter, Gmail, or Pocket apps use flat custom view in the list UI.

The main advantage of using flat custom view is that it can greatly compress the view level of the app, so that it can perform faster layout element traversal and ultimately reduce memory usage.

Flat custom view gives you the greatest freedom, as if you were painting on a blank sheet of paper. However, such freedom has a price: you cannot use the existing view elements, suchTextViewAndImageView. Yes, inCanvasIt is really easy to describe the text above, but what if you want to implement ellipsizing (that is, truncate too long text? SimilarlyCanvasThe image above is simple, but how can we scale it? These restrictions also apply to touch events, accessibility, keyboard navigation, and so on.

Therefore, the bottom line for using flat custom view is to apply flat custom view only to the core UI part of your app. Others directly depend on the view provided by the Android platform.

TweetElementViewThe code is flat custom view. To implement it more easily, I created a small custom view framework calledUIElement. You canCanvasFind it in the code package.

UIElementProvides the measure/layout API similar to the Android platform. It containsTextViewAndImageViewThese two elements contain several required features-seeTextElementCode andImageElementCode. It also has its own inflatercode to help instantiate the code from the layout resource fileUIElement.

Note:UIElementIt is still in a very early stage of development, so there are still many defects, but with the continuous improvement in the futureUIElementIt may become very useful.

You may thinkTweetElementViewThe code looks very simple, because the actual code isTweetElementCode-actuallyTweetElementViewThe code that assumes the hosted role.

TweetElementLayout code andTweetLayoutView'Is very similar, but it uses Picasso to request an image but it does not have the same code, becauseTweetElementNot usedImageView.

Async Custom View

In general, the Android UI framework is single-threaded. Such a single thread will impose some restrictions. For example, you cannot traverse layout elements outside the main thread-however, this is very beneficial to the complex and dynamic UI.

Assume that your app is inListViewIs very complex (just like most social apps), you are movingListViewIt is very likely that frame skipping occurs, becauseListViewYou need to calculate the View Size code and layout code for the new content to be displayed in the list. The same problem also occursGridViews,ViewPagersAnd so on.

Can we solve the above problem if we can traverse the layout of those child views on the threads other than the main thread? That is to say, callMeasure ()AndLayout ()Methods do not occupy the Time of the main thread.

SoAsync custom viewThis is an experiment that allows the sub-view layout traversal process to happen outside the main thread. This idea was inspired by Facebook's Paperteam async node framework video.

Since we will never be able to access the UI components of the Android platform outside the main thread, we need an API to measure and layout the content of this view without being able to directly access this view. This is exactlyUIElementThe functions provided by the framework.

AsyncTweetViewCode is an async custom view. It uses a thread-safeAsyncTweetElementCode factory class code to define its content. The specific process is that the code of an Smoothie subitem loader is temporarily invisible on a background thread.AsyncTweetElementCreate, pre-measure, and cache (in the memory for later use ).

Of course, I have compromised some implementation of this asynchronous UI, because you do not know how to display layout placeholders of any height. For example, when the layout is passed asynchronously, you can only change the size of the layout in the background thread once. Therefore, whenAsyncTweetViewIt cannot be found in the memory when it needs to be displayed.AsyncTweetElementIn this case, the framework will force the creation ofAsyncTweetElementCode.

In addition, the pre-loaded logic and memory cache expiration time settings must be well implemented to ensure that the cache layout in the memory is used as much as possible in the main thread. For example, using LRU to cache code in this solution is not a wise choice.

Despite these limitations, the preliminary results of Using async M view are promising. Of course, I will continue to explore this field by restructuring this UIElement framework and using other types of UIS. Let's stay tuned.

Summary

The deeper we define the layout, the less dependencies we can obtain from the Android platform. Therefore, we also need to avoid premature optimization. We can customize the layout only in areas that can actually improve the app quality and performance.

This is not a non-black-white decision. There are also many solutions between using the platform's UI elements and completely customized two extremes-from simple composite views to complex async views. In actual projects, you may write excellent apps in combination with several solutions in the article.


Related Article

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.