The implementation of streaming layouts for popular tags common in Android

Source: Internet
Author: User

First, overview:
In everyday app use, we'll see a streaming layout of popular tags and more in Android apps, and today we'll see how

Customize a streaming layout like a hot tag ( source download is given below )

A similar custom layout. Let's take a detailed introduction to the application features of streaming layouts and the technical points used:

1. Flow layout features and application scenarios
Features: When the upper line of space is not enough to accommodate the new TextView,
To open up the next line of space.

Schematic diagram:

  

Scenario: Mainly used for keywords search or popular tags and other scenes
2. Custom ViewGroup, focus on rewriting the following two methods

1, onmeasure: Measure the height of the sub-view, set their own width and height

2. OnLayout: Set the location of the child view

Onmeasure: Sets the measurement mode and measurement values for child view according to the attributes in the layout file of the child view
Measurement = measurement mode + measured value;

There are 3 modes of measurement:
Exactly: Indicates that the exact value is set, generally, when Childview is set to its width, height is the exact value, Match_parent, ViewGroup will set it to exactly;
At_most: Indicates that the sub-layout is limited to a maximum value, generally when Childview set its width, height is wrap_content, ViewGroup will set it to At_most;
UNSPECIFIED: Indicates how large the sub-layout wants, usually appears in the Aadapterview item's Heightmode, ScrollView Childview heightmode; This pattern is relatively rare.
3.LayoutParams
ViewGroup layoutparams: Each viewgroup corresponds to a layoutparams; ViewGroup, Layoutparams
Getlayoutparams do not know which corresponding layoutparams, in fact, is very simple, is as follows:
The layoutparams corresponding to the child view.getlayoutparams is the layoutparams of the parent control where the child view resides;
For example, the linearlayout inside of the child view.getlayoutparams->linearlayout.layoutparams
So our flowlayout also need a layoutparams, because the above is the margin of the child view,
So you should use Marginlayoutparams. namely Flowlayout->marginlayoutparams

4. Finally, take a look at the final implementation:


Second, the popular label Flow layout implementation:

1. Customizing the ViewGroup implementation of popular tags

Based on the technical analysis above, the custom class inherits from the ViewGroup and overrides methods such as Onmeasure and OnLayout. The specific implementation code is as follows:

Package Com.czm.flowlayout;import Java.util.arraylist;import Java.util.list;import android.content.context;import Android.util.attributeset;import android.view.view;import android.view.viewgroup;/** * * @author caizhiming * @created On 2015-4-13 */public class Xcflowlayout extends viewgroup{//store all child View private list<list<view>> Mallchi    Ldviews = new arraylist<> ();        Height of each line private list<integer> mlineheight = new arraylist<> ();        Public Xcflowlayout (Context context) {This (context, NULL); TODO auto-generated Constructor stub} public xcflowlayout (context context, AttributeSet Attrs) {This (con        Text, attrs, 0);        TODO auto-generated Constructor stub} public xcflowlayout (context context, AttributeSet attrs, int defstyle) {        Super (context, attrs, Defstyle); TODO auto-generated Constructor stub} @Override protected void onmeasure (int widthmeasurespec, int heightmeas URESPEC) {        TODO auto-generated Method Stub//parent control passed in width and height as well as corresponding measurement mode int sizewidth = Measurespec.getsi        Ze (widthmeasurespec);        int modewidth = Measurespec.getmode (Widthmeasurespec);        int sizeheight = measurespec.getsize (Heightmeasurespec);                int modeheight = Measurespec.getmode (Heightmeasurespec);        If the width of the current viewgroup is wrap_content of the case int width = 0;//own measured width int height = 0;//own measured height//record width and height of each row        int linewidth = 0;                int lineheight = 0;        Gets the number of child view int childCount = Getchildcount ();            for (int i = 0;i < ChildCount; i + +) {View child = Getchildat (i);            Measure sub-view width and height measurechild (child, Widthmeasurespec, Heightmeasurespec);            Get layoutparams marginlayoutparams LP = (marginlayoutparams) getlayoutparams ();            The child view occupies a width of int childwidth = Child.getmeasuredwidth () + Lp.leftmargin + lp.rightmargin; Sub VIew occupies a height of int childheight = Child.getmeasuredheight () + Lp.topmargin + lp.bottommargin; Line break if (linewidth + childwidth > Sizewidth) {//compare to get maximum width = Math.max (wi                DTH, linewidth);                Reset LineWidth linewidth = childwidth;                Record line High height + = lineheight;            Lineheight = Childheight;                }else{//No Line break//Overlay line width linewidth + = childwidth;            Get maximum row height lineheight = Math.max (lineheight, childheight);                }//Handle the case of the last child view if (i = = childCount-1) {width = Math.max (width, linewidth);            Height + = lineheight;                }}//wrap_content setmeasureddimension (modewidth = = measurespec.exactly? sizewidth:width, Modeheight = = measurespec.exactly?        Sizeheight:height); Super.onmeasure (widthmeasurespec, heightMEASURESPEC);  } @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {//TODO auto-generated        Method stub mallchildviews.clear ();        Mlineheight.clear ();                Gets the width of the current viewgroup int width = getwidth ();        int linewidth = 0;        int lineheight = 0;        Record the current line of View list<view> lineviews = new arraylist<view> ();        int childCount = Getchildcount ();            for (int i = 0;i < ChildCount; i + +) {View child = Getchildat (i);            Marginlayoutparams LP = (marginlayoutparams) child.getlayoutparams ();            int childwidth = Child.getmeasuredwidth ();                        int childheight = Child.getmeasuredheight ();                If you need line break if (childwidth + linewidth + lp.leftmargin + lp.rightmargin > width) {//Record lineheight                Mlineheight.add (lineheight);     Record the current line of views Mallchildviews.add (Lineviews);           Resets the line's width to height linewidth = 0;                Lineheight = childheight + Lp.topmargin + lp.bottommargin;            Resets the collection of view lineviews = new ArrayList ();            } linewidth + = childwidth + Lp.leftmargin + lp.rightmargin;            Lineheight = Math.max (lineheight, childheight + lp.topmargin + lp.bottommargin);        Lineviews.add (child);        }//processing the last line Mlineheight.add (lineheight);                Mallchildviews.add (lineviews);        Sets the position of the child view int left = 0;        int top = 0;        Gets the number of rows int linecount = Mallchildviews.size ();            for (int i = 0; i < linecount; i + +) {//When forward views and heights Lineviews = Mallchildviews.get (i);            Lineheight = Mlineheight.get (i);                for (int j = 0; J < Lineviews.size (); j + +) {View child = Lineviews.get (j); Determines whether to show if (child.getvisibility () = = View.gone) {ContiNue                } marginlayoutparams LP = (marginlayoutparams) child.getlayoutparams ();                int cleft = left + lp.leftmargin;                int ctop = top + lp.topmargin;                int cright = cleft + child.getmeasuredwidth ();                int cbottom = ctop + child.getmeasuredheight ();                Perform sub-view layout child.layout (cleft, ctop, Cright, cbottom);            Left + = Child.getmeasuredwidth () + Lp.leftmargin + lp.rightmargin;            } left = 0;        Top + = Lineheight; }}/** * corresponds to the current viewgroup Layoutparams */@Override public layoutparams generatelayoutparams (at Tributeset attrs) {//TODO auto-generated method stub return new Marginlayoutparams (GetContext (), a    TTRS); }}

2. Related Layout files:

To reference a custom control:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:id=" @+id/container "    android:layout_width=" Match_parent "    Android : layout_height= "Match_parent" >    <com.czm.flowlayout.xcflowlayout        android:id= "@+id/flowlayout"        android:layout_width= "match_parent"        android:layout_height= "match_parent" >    </ Com.czm.flowlayout.xcflowlayout></relativelayout>

TextView Style Files:

<?xml version= "1.0" encoding= "Utf-8"? ><shape xmlns:android= "Http://schemas.android.com/apk/res/android" >    <solid android:color= "#666666"/>    <corners android:radius= "10DP"/>    <padding         android:left= "5DP"        android:right= "5DP"        android:top= "5DP"        android:bottom= "5DP"         /></shape >

Third, use the custom layout control class

Finally, how do you use this custom hot tag control class? Very simple, take a look at the following example code:

Package Com.czm.flowlayout;import Android.app.activity;import Android.graphics.color;import android.os.Bundle; Import Android.view.viewgroup.layoutparams;import Android.view.viewgroup.marginlayoutparams;import     android.widget.textview;/** * * @author caizhiming * @created on 2015-4-13 */public class Mainactivity extends Activity {            Private String mnames[] = {"Welcome", "Android", "TextView", "Apple", "Jamy", "Kobe Bryant",     "Jordan", "Layout", "ViewGroup", "margin", "padding", "text", "name", "type", "Search", "Logcat"};    Private Xcflowlayout mflowlayout;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main);            Initchildviews (); } private void Initchildviews () {//TODO auto-generated method Stub mflowlayout = (Xcflowlayout) Findvie        Wbyid (r.id.flowlayout); Marginlayoutparams LP = new MarGinlayoutparams (layoutparams.wrap_content,layoutparams.wrap_content);        Lp.leftmargin = 5;        Lp.rightmargin = 5;        Lp.topmargin = 5;        Lp.bottommargin = 5;            for (int i = 0; i < mnames.length; i + +) {TextView view = new TextView (this);            View.settext (Mnames[i]);            View.settextcolor (Color.White);            View.setbackgrounddrawable (Getresources (). getdrawable (R.DRAWABLE.TEXTVIEW_BG));        Mflowlayout.addview (VIEW,LP); }    }}

Iv. Source code Download

Finally give the source code download:http://download.csdn.net/detail/jczmdeveloper/8590113

After this source download, often there is a key point we are easy to ignore, that is the source of security issues, here you can click the Mobile app Security Intelligence service provider Love encrypted Android encryption , source protection !

The implementation of streaming layouts for popular tags common in Android

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.