Summary of usage of Android custom view

Source: Internet
Author: User

This article refers to the following: http://greenrobot.me/devpost/android-custom-layout/

There are a number of UI components available in the Android SDK, such as Relativelayout, LinearLayout, etc., and there are two major advantages to using custom controls:
1. Increase UI display efficiency by reducing the use of view
2. Build controls that are not in the SDK

The original text summarizes 4 custom views, namely Composite view, custom Composite view, Flat custom view and async custom views. The sample code is https://github.com/lucasr/android-layout-samples and can be run directly. The project relies on two projects:Picassoand theSmoothie. Picasso

Picasso is an asynchronous picture loading library, smoothie provides an interface for loading the ListView and GridView Data Items asynchronously, which makes the loading of the list data more smooth.

This article only introduces Composite Vew and custom Composite view methods, both of which are sufficient for us to use, the remaining two methods need to customize a set of control view framework, maintenance cost is high, recommended only in the app's core and stable UI, Interested readers can study it by themselves.


Composite View
This method is the simplest way to combine multiple view into a reusable view, as follows:
1. Custom control, inherit the corresponding control.
2. Fill in the constructor with a merge layout
3. Initialize the internal view in the custom control

4. Provide the interface to refresh the view

A usage is described below, as shown in the layout of the view:


The first is to define a class file Tweetcompositeview.java

public class Tweetcompositeview extends Relativelayout implements Tweetpresenter {private final ImageView Mprofileimag    E    Private final TextView Mauthortext;    Private final TextView Mmessagetext;    Private final ImageView Mpostimage;    Private final enummap<action, imageview> mactionicons;    Public Tweetcompositeview (context context, AttributeSet Attrs) {This (context, attrs, 0); } public Tweetcompositeview (context context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, defst        YLEATTR);        Layoutinflater.from (context). Inflate (R.layout.tweet_composite_view, this, true);        Initialize Internal member Variable Mprofileimage = (ImageView) Findviewbyid (r.id.profile_image);        Mauthortext = (TextView) Findviewbyid (R.id.author_text);        Mmessagetext = (TextView) Findviewbyid (R.id.message_text);        Mpostimage = (ImageView) Findviewbyid (r.id.post_image);        Mactionicons = new Enummap (action.class); for (Action Action:Action.valueS ()) {final ImageView icon;                    Switch (action) {Case Reply:icon = (ImageView) Findviewbyid (r.id.reply_action);                Break                    Case Retweet:icon = (ImageView) Findviewbyid (r.id.retweet_action);                Break                    Case Favourite:icon = (ImageView) Findviewbyid (r.id.favourite_action);                Break            Default:throw New IllegalArgumentException ("unrecognized tweet action");        } Mactionicons.put (action, icon);    }} @Override public boolean shoulddelaychildpressedstate () {return false; }//interface that provides update UI @Override public void Update (tweet, enumset<updateflags> flags) {mauthortext.se        Ttext (Tweet.getauthorname ());        Mmessagetext.settext (Tweet.getmessage ());        Final context context = GetContext (); Imageutils.loadimage (context, Mprofileimage, Tweet.getprofileimageurl (), flags); Final Boolean haspostimage =!        Textutils.isempty (Tweet.getpostimageurl ()); Mpostimage.setvisibility (haspostimage?        View.VISIBLE:View.GONE);        if (haspostimage) {imageutils.loadimage (context, Mpostimage, Tweet.getpostimageurl (), flags); }    }}
The class inherits from Relativelayout and implements the Tweetpresenter interface to update the UI. Initializes the internal view in the constructor

Merge tag in layout file Tweet_composite_view.xml reduces the level of layout

<?xml version= "1.0" encoding= "Utf-8"? ><merge xmlns:android= "Http://schemas.android.com/apk/res/android" Android:layout_width= "Match_parent" android:layout_height= "match_parent" > <imageview android:id= "@+id/p Rofile_image "android:layout_width=" @dimen/tweet_profile_image_size "android:layout_height=" @dimen/tweet_pro File_image_size "android:layout_marginright=" @dimen/tweet_content_margin "android:scaletype=" CenterCrop "/&gt    ; <textview android:id= "@+id/author_text" android:layout_width= "Fill_parent" android:layout_height= "        Wrap_content "android:layout_torightof=" @id/profile_image "android:layout_aligntop=" @id/profile_image " Android:textcolor= "@color/tweet_author_text_color" android:textsize= "@dimen/tweet_author_text_size" Androi        D:singleline= "true"/> <textview android:id= "@+id/message_text" android:layout_width= "Fill_parent" Android:layout_height= "Wrap_content" android:layout_below= "@id/author_text" android:layout_alignleft= "@id/author_text" a Ndroid:textcolor= "@color/tweet_message_text_color" android:textsize= "@dimen/tweet_message_text_size"/> <Im Ageview android:id= "@+id/post_image" android:layout_width= "fill_parent" android:layout_height= "@dimen /tweet_post_image_height "android:layout_below=" @id/message_text "android:layout_alignleft=" @id/message_text "Android:layout_margintop=" @dimen/tweet_content_margin "android:scaletype=" Centercrop "/> <LinearLa Yout android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:layout_below= "@id/post_        Image "android:layout_alignleft=" @id/message_text "android:layout_margintop=" @dimen/tweet_content_margin " android:orientation= "Horizontal" > <imageview android:id= "@+id/reply_action" Androi    D:layout_width= "0DP"        android:layout_height= "@dimen/tweet_icon_image_size" android:layout_weight= "1" android:src= " @drawable/tweet_reply "android:scaletype=" Fitstart "/> <imageview android:id=" @+id/retwe            Et_action "android:layout_width=" 0DP "android:layout_height=" @dimen/tweet_icon_image_size "        android:layout_weight= "1" android:src= "@drawable/tweet_retweet" android:scaletype= "Fitstart"/> <imageview android:id= "@+id/favourite_action" android:layout_width= "0DP" Androi d:layout_height= "@dimen/tweet_icon_image_size" android:layout_weight= "1" android:src= "@drawable/twee T_favourite "android:scaletype=" Fitstart "/> </LinearLayout></merge>

This method of custom view usage is simple and easy to maintain. However, there are more UI sub-view of custom view in this way, which will affect the traversal efficiency for complex view. Open the Show layout boundaries option in the phone settings as follows:


Some controls, such as Relativelayout,linearlayout, are required to traverse child view multiple times to determine their own properties, such as LinearLayout's weight property. If you can customize the calculation and positioning logic for your own apps, you can greatly optimize the traversal of your UI. This approach is the custom Composite View that is introduced next


Custom Composite View

Compared to the Composite view method, a custom Composite view inherits from a ViewGroup and implements the Onmeasure and OnLayout methods. The Tweetlayoutview below is a custom Composite View.

Tweetlayoutview.java

public class Tweetlayoutview extends ViewGroup implements Tweetpresenter {private final ImageView mprofileimage;    Private final TextView Mauthortext;    Private final TextView Mmessagetext;    Private final ImageView Mpostimage;    Private final enummap<action, view> mactionicons;    Public Tweetlayoutview (context context, AttributeSet Attrs) {This (context, attrs, 0); } public Tweetlayoutview (context context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, Defstyle        ATTR);        Layoutinflater.from (context). Inflate (R.layout.tweet_layout_view, this, true);        Mprofileimage = (ImageView) Findviewbyid (r.id.profile_image);        Mauthortext = (TextView) Findviewbyid (R.id.author_text);        Mmessagetext = (TextView) Findviewbyid (R.id.message_text);        Mpostimage = (ImageView) Findviewbyid (r.id.post_image);        Mactionicons = new Enummap (action.class);      For (Action action:Action.values ()) {final int viewId;      Switch (action) {case reply:viewid = r.id.reply_action;                Break                    Case retweet:viewid = r.id.retweet_action;                Break                    Case favourite:viewid = r.id.favourite_action;                Break            Default:throw New IllegalArgumentException ("unrecognized tweet action");        } mactionicons.put (Action, Findviewbyid (ViewId));  }} private void Layoutview (view view, int left, int top, int width, int height) {marginlayoutparams margins        = (marginlayoutparams) view.getlayoutparams ();        Final int leftwithmargins = left + margins.leftmargin;        Final int topwithmargins = top + margins.topmargin;    View.layout (Leftwithmargins, Topwithmargins, Leftwithmargins + width, topwithmargins + height); } private int Getwidthwithmargins (View child) {finAL marginlayoutparams lp = (marginlayoutparams) child.getlayoutparams ();    return Child.getwidth () + Lp.leftmargin + lp.rightmargin; } private int Getheightwithmargins (View child) {FINAL Marginlayoutparams LP = (marginlayoutparams) child.getlay        Outparams ();    return Child.getmeasuredheight () + Lp.topmargin + lp.bottommargin; } private int Getmeasuredwidthwithmargins (View child) {FINAL Marginlayoutparams LP = (marginlayoutparams) Child        . Getlayoutparams ();    return Child.getmeasuredwidth () + Lp.leftmargin + lp.rightmargin; } private int Getmeasuredheightwithmargins (View child) {FINAL Marginlayoutparams LP = (marginlayoutparams) chil        D.getlayoutparams ();    return Child.getmeasuredheight () + Lp.topmargin + lp.bottommargin;    } @Override public Boolean shoulddelaychildpressedstate () {return false; } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {final int widthsize =Measurespec.getsize (WIDTHMEASURESPEC);        int widthused = 0;        int heightused = 0;                                Measurechildwithmargins (Mprofileimage, Widthmeasurespec, widthused,        Heightmeasurespec, heightused);        widthused + = Getmeasuredwidthwithmargins (mprofileimage);                                Measurechildwithmargins (Mauthortext, Widthmeasurespec, widthused,        Heightmeasurespec, heightused);        heightused + = Getmeasuredheightwithmargins (Mauthortext);                                Measurechildwithmargins (Mmessagetext, Widthmeasurespec, widthused,        Heightmeasurespec, heightused);        heightused + = Getmeasuredheightwithmargins (Mmessagetext);                                    if (mpostimage.getvisibility ()! = View.gone) {measurechildwithmargins (Mpostimage, Widthmeasurespec, widthused, HeightmeasuRespec, heightused);        heightused + = Getmeasuredheightwithmargins (mpostimage);        } int maxiconheight = 0;            For (Action Action:Action.values ()) {final View IconView = Mactionicons.get (action);                                    Measurechildwithmargins (IconView, Widthmeasurespec, widthused,            Heightmeasurespec, heightused);            Final int height = getmeasuredheightwithmargins (iconview);            if (height > maxiconheight) {maxiconheight = height;        } widthused + = Getmeasuredwidthwithmargins (IconView);        } heightused + = Maxiconheight;        int heightsize = heightused + getpaddingtop () + Getpaddingbottom ();    Setmeasureddimension (Widthsize, heightsize); } @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {final int paddingleft = GE        Tpaddingleft ();   Final int paddingtop = Getpaddingtop ();     int currenttop = paddingtop; Layoutview (Mprofileimage, Paddingleft, Currenttop, Mprofileimage.getmeasuredwidth (), M        Profileimage.getmeasuredheight ());        Final int contentleft = Getwidthwithmargins (mprofileimage) + paddingleft;        Final int contentwidth = r-l-Contentleft-getpaddingright ();        Layoutview (Mauthortext, Contentleft, Currenttop, Contentwidth, Mauthortext.getmeasuredheight ());        Currenttop + = Getheightwithmargins (Mauthortext);        Layoutview (Mmessagetext, Contentleft, Currenttop, Contentwidth, Mmessagetext.getmeasuredheight ());        Currenttop + = Getheightwithmargins (Mmessagetext);                       if (mpostimage.getvisibility () = View.gone) {Layoutview (Mpostimage, Contentleft, Currenttop,            Contentwidth, Mpostimage.getmeasuredheight ());        Currenttop + = Getheightwithmargins (mpostimage); } final int iconswidth = Contentwidth /Mactionicons.size ();        int iconsleft = Contentleft;            For (Action Action:Action.values ()) {final View icon = mactionicons.get (action);            Layoutview (icon, Iconsleft, Currenttop, Iconswidth, Icon.getmeasuredheight ());        Iconsleft + = Iconswidth; }} @Override public layoutparams generatelayoutparams (AttributeSet attrs) {return new marginlayoutparams    (GetContext (), attrs); } @Override protected Layoutparams generatedefaultlayoutparams () {return new Marginlayoutparams (layoutparams .    Wrap_content, layoutparams.wrap_content); } @Override public void update (tweet, enumset<updateflags> flags) {Mauthortext.settext (tweet.get        AuthorName ());        Mmessagetext.settext (Tweet.getmessage ());        Final context context = GetContext ();        Imageutils.loadimage (context, Mprofileimage, Tweet.getprofileimageurl (), flags); Final Boolean haspostimage =! Textutils.iSempty (Tweet.getpostimageurl ()); Mpostimage.setvisibility (haspostimage?        View.VISIBLE:View.GONE);        if (haspostimage) {imageutils.loadimage (context, Mpostimage, Tweet.getpostimageurl (), flags); }    }}

of this classclothThe local file is still tweet_composite_view.xml, the constructor initializes the internal view, unlike the composite view, which determines the size and position of the internal view by overloading the Onmeasure and OnLayout methods.The basic idea is that the process passes through ViewGroup's measurechildwithmargins () method and behind the Getchildmeasurespec () Method calculates the measurespec of each child view . The layout hierarchy of this custom view is the same as that of the composite view, but the view is less expensive to traverse than the former.


If you want to further optimize the key parts of the UI, such as the ListView and GridView, consider combining the custom Composite view into a single view unified management, so that the resulting view hierarchy is as shown:


To achieve this effect, you need to refer to flat custom view's customized view mode, just interested readers can refer to the source code.


Summary of usage of Android custom view

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.