Anroid ListView Grouping and Suspension Header realization Method _android

Source: Internet
Author: User

Before using iOS, see a grouped view, each group has a header, sliding up and down, there will be a floating header, this experience is very good, please look at the following figure:

In the picture above, the red 1,2,3,4 four picture, when the upward slide, carefully observe the gray bar header changes, when the second group to slide up, will be the first group of suspension header squeeze up.

This effect is not on Android, and the iOS SDK has this effect on its own. This article describes how to achieve this effect on Android.

1, the implementation of the suspension header

In fact, Android comes with the contact of the app has such a effect, I also took his class directly, to achieve a pinnedheaderlistview such a class, extended in ListView, The core principle is to draw the header view of the caller set at the top of the ListView, and to move the header view up or down according to some states when sliding, in fact, to call its layout method, In theory, it is also possible to make some translations there. Here is a specific implementation:

1.1, Pinnedheaderadapter interface

This interface needs to be implemented by ListView adapter, which defines two methods, one that lets adapter tell ListView the status of the currently specified position data, such as specifying that the position data may be the header of the group Another approach is to set header view, such as text for header view, picture, and so on, which is implemented by the caller.

/** * Adapter interface. 
 The list adapter must implement this interface. 
   * * Public interface Pinnedheaderadapter {/** * Pinned header State:don ' t show the header. 
 
  * * public static final int pinned_header_gone = 0; 
   /** * Pinned Header state:show The header at the top of the list. 
 
  * * public static final int pinned_header_visible = 1; /** * Pinned Header state:show the header. 
   If the header extends beyond * The bottom of the ' the ' the ' the ' the ' the ', Push it up and clip. 
 
  * * public static final int pinned_header_pushed_up = 2; /** * Computes the desired state's pinned header for the given * position of the The ' the ' the ' the ' the ' the ' the ' the '. Allowed return values are * {@link #PINNED_HEADER_GONE}, {@link #PINNED_HEADER_VISIBLE} or * {@link #PINNED_HEADER 
   _PUSHED_UP}. 
 
  * * int getpinnedheaderstate (int position); 
   /** * Configures the pinned header view to match the ' the '. * * @param Header pinned header view. 
   * @param position position of the the ' the ' visible list item. 
   * @param alpha Fading of the header view, between 0 and 255. 
*/void Configurepinnedheader (View header, int position, int alpha); 
 }

1.2. How to draw header View

This is plotted in the Dispatchdraw method:

@Override 
protected void Dispatchdraw (Canvas Canvas) { 
  super.dispatchdraw (Canvas); 
  if (mheaderviewvisible) { 
    drawchild (canvas, Mheaderview, Getdrawingtime ()); 
   

1.3. Configure Header View

The core is based on different status values to control the status of the HEADER View, such as Pinned_header_gone (hidden) situation, you may need to set a flag tag, do not draw HEADER view, then achieve a hidden effect. When Pinned_header_pushed_up state, the moving displacement of HEADER view may need to be calculated according to different displacements. The following are the specific implementations:

public void Configureheaderview (int position) {if (Mheaderview = null | | | null = = madapter) {return; 
  int state = madapter.getpinnedheaderstate (position); 
      Switch (state) {case Pinnedheaderadapter.pinned_header_gone: {mheaderviewvisible = false; 
    Break Case pinnedheaderadapter.pinned_header_visible: {madapter.configurepinnedheader (Mheaderview, Position, MA 
      X_alpha); 
      if (mheaderview.gettop ()!= 0) {mheaderview.layout (0, 0, mheaderviewwidth, mheaderviewheight); 
      } mheaderviewvisible = true; 
    Break 
      Case PINNEDHEADERADAPTER.PINNED_HEADER_PUSHED_UP: {View firstview = getchildat (0); 
       int bottom = Firstview.getbottom (); 
      int itemheight = Firstview.getheight (); 
      int headerheight = Mheaderview.getheight (); 
      int y; 
      int Alpha; 
        if (bottom < headerheight) {y = (bottom-headerheight); Alpha = Max_alpha * (HeaderheigHT + y)/headerheight; 
        else {y = 0; 
      Alpha = Max_alpha; 
      } madapter.configurepinnedheader (Mheaderview, position, Alpha); 
      if (Mheaderview.gettop ()!= y) {mheaderview.layout (0, Y, mheaderviewwidth, mheaderviewheight + y); 
      } mheaderviewvisible = true; 
    Break 
 } 
  } 
}

1.4, OnLayout and Onmeasure

In both of these methods, control the position and size of the header view

@Override 
protected void onmeasure (int widthmeasurespec, int heightmeasurespec) { 
  super.onmeasure ( Widthmeasurespec, Heightmeasurespec); 
  if (Mheaderview!= null) { 
    measurechild (Mheaderview, Widthmeasurespec, heightmeasurespec); 
    Mheaderviewwidth = Mheaderview.getmeasuredwidth (); 
    Mheaderviewheight = Mheaderview.getmeasuredheight (); 
  } 
} 
 
@Override 
protected void OnLayout (Boolean changed, int left, int. top, int right, int bottom) { 
  super.onlayout (ch Anged, left, top, right, bottom); 
  if (Mheaderview!= null) { 
    mheaderview.layout (0, 0, mheaderviewwidth, mheaderviewheight); 
    Configureheaderview (Getfirstvisibleposition ()); 
  } 
 

OK, here, Suspension header view is over, you may not see the complete code, as long as you understand these core methods, write it out, and almost.

2, ListView section implementation

There are two ways to implement the ListView Section effect:

Method One:

Each itemview contains headers, the data to control their display or hidden, the principle of implementation of the following diagram:

Advantages:

1, simple to achieve, in the implementation of Adapter.getview, only need to judge according to the data is header, not, Hide Item View header part, otherwise display.

2,adapter.getitem (int n) always returns the data that corresponds to the nth data in the list of data, which is easy to understand.

3, it is easier to control the header's Click event

Disadvantages:
1, the use of more memory, the first item view contains a header view, so that more memory dues, most of the time may be the header is hidden.

Method Two:

Use different types of view: overriding the Getitemviewtype (int) and Getviewtypecount () methods.

Advantages:

1, allows multiple different types of item

2, easier to understand

Disadvantages:

1, the implementation is more complex

2, getting the data at the specified location becomes more complicated

Here, my implementation is to choose the second scenario, although it is implemented in a more complex way, but the advantages are obvious.

3, the realization of adapter

This is basically the realization of the two methods of Getpinnedheaderstate and Configurepinnedheader

Private class Listviewadapter extends Baseadapter implements Pinnedheaderadapter {private Arraylist<contact&gt ; 
  Mdatas;  
  private static final int type_category_item = 0;  
   
  private static final int type_item = 1; 
  Public Listviewadapter (arraylist<contact> datas) {mdatas = datas; 
  @Override public boolean areallitemsenabled () {return false; @Override public boolean isenabled (int position) {//exception handling if (null = = Mdatas | | position < 0| | 
    Position > GetCount ()) {return true; 
    Contact item = mdatas.get (position); 
    if (item.issection) {return false; 
  return true; 
  @Override public int GetCount () {return mdatas.size (); @Override public int Getitemviewtype (int position) {//exception handling if (null = = Mdatas | | position < 0| | 
    Position > GetCount ()) {return type_item; Contact item = MDAtas.get (position); 
    if (item.issection) {return type_category_item; 
  return type_item; 
  @Override public int Getviewtypecount () {return 2; @Override public Object getitem (int position) {return (position >= 0 && Position < mdatas.si Ze ())? 
  Mdatas.get (position): 0; 
  @Override public long getitemid (int position) {return 0; @Override public View getview (int position, View Convertview, viewgroup parent) {int itemviewtype = Getite 
    Mviewtype (position); 
    Contact data = (Contact) getitem (position); 
     
    TextView Itemview; Switch (itemviewtype) {case type_item:if (null = = Convertview) {Itemview = new TextView (sectionlis 
        Tview.this); 
        Itemview.setlayoutparams (New Abslistview.layoutparams (ViewGroup.LayoutParams.MATCH_PARENT, mitemheight)); 
        Itemview.settextsize (16); 
      Itemview.setpadding (10, 0, 0, 0);  Itemview.setgravity (gravity.center_vertical); 
        Itemview.setbackgroundcolor (Color.argb (255, 20, 20, 20)); 
      Convertview = Itemview; 
      } Itemview = (TextView) Convertview; 
      Itemview.settext (Data.tostring ()); 
       
    Break 
      Case Type_category_item:if (null = = Convertview) {Convertview = Getheaderview (); 
      } Itemview = (TextView) Convertview; 
      Itemview.settext (Data.tostring ()); 
    Break 
  return convertview; @Override public int getpinnedheaderstate (int position) {if (position < 0) {return Pinned_heade 
    R_gone; 
    Contact item = (contact) getitem (position); 
    Contact Itemnext = (Contact) getitem (position + 1); 
    Boolean issection = Item.issection; Boolean isnextsection = (null!= itemnext)? 
    ItemNext.isSection:false; 
    if (!issection && isnextsection) {return pinned_header_pushed_up; } RETurn pinned_header_visible; @Override public void Configurepinnedheader (View header, int position, int alpha) {Contacts item = (Contact 
    ) GetItem (position); 
      if (null!= item) {if (header instanceof TextView) {(TextView) header). SetText (ITEM.SECTIONSTR); 
 } 
    } 
  } 
}

In the Getpinnedheaderstate method, if the first item is not a section and the second item is a section, the state pinned_header_pushed_up is returned, otherwise the Pinned_header_ VISIBLE.
In the Configurepinnedheader method, you set the section string of the item to header view.

"Important note"

The data in adapter already contains the section (header) data, and there is a method in the data structure to identify whether it is a section. Then, in the event of a click, it is necessary to note that the section data structure may be returned via position.

The data structure contact is defined as follows:

public class Contact { 
  int id; 
  String name; 
  String Pinyin; 
  String sortletter = "#"; 
  String Sectionstr; 
  String PhoneNumber; 
  Boolean issection; 
  static Characterparser sparser = Characterparser.getinstance (); 
   
  Contact () { 
     
  } contacts 
   
  (int id, String name) { 
    this.id = ID; 
    this.name = name; 
    This.pinyin = sparser.getspelling (name); 
    if (! textutils.isempty (Pinyin)) { 
      String sortstring = this.pinyin.substring (0, 1). toUpperCase (); 
      if (Sortstring.matches ("[A-z]")) { 
        this.sortletter = Sortstring.touppercase (); 
      } else { 
        This.sortletter = "#"; 
   
  }} @Override public 
  String toString () { 
    if (issection) { 
      .} {return name 
    } else { 
      //return name + "(" + Sortletter + "," + Pinyin + ")"; 
      Return name + ("+ PhoneNumber +") ";}}} 
  

The complete code

Package com.lee.sdk.test.section; 
 
Import java.util.ArrayList; 
Import Android.graphics.Color; 
Import Android.os.Bundle; 
Import android.view.Gravity; 
Import Android.view.View; 
Import Android.view.ViewGroup; 
Import Android.widget.AbsListView; 
Import Android.widget.AdapterView; 
Import Android.widget.AdapterView.OnItemClickListener; 
Import Android.widget.BaseAdapter; 
Import Android.widget.TextView; 
 
Import Android.widget.Toast; 
Import com.lee.sdk.test.GABaseActivity; 
Import COM.LEE.SDK.TEST.R; 
Import Com.lee.sdk.widget.PinnedHeaderListView; 
 
Import Com.lee.sdk.widget.PinnedHeaderListView.PinnedHeaderAdapter; 
  public class Sectionlistview extends gabaseactivity {private int mitemheight = 55; 
   
  private int msecheight = 25; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
     
    Setcontentview (R.layout.activity_main); 
    float density = getresources (). Getdisplaymetrics (). density; MitemheigHT = (int) (density * mitemheight); 
     
    Msecheight = (int) (density * msecheight); 
    Pinnedheaderlistview Mlistview = new Pinnedheaderlistview (this); 
    Mlistview.setadapter (New Listviewadapter (Contactloader.getinstance (). Getcontacts (this)); 
    Mlistview.setpinnedheaderview (Getheaderview ()); 
    Mlistview.setbackgroundcolor (Color.argb (255, 20, 20, 20)); Mlistview.setonitemclicklistener (New Onitemclicklistener () {@Override public void Onitemclick (ADAPTERVIEW&L t;? > Parent, view view, int position, long ID) {Listviewadapter adapter = ((Listviewadapter) Parent.getadapter () 
        ); 
        Contact data = (Contact) adapter.getitem (position); 
      Toast.maketext (Sectionlistview.this, data.tostring (), Toast.length_short). Show (); 
 
    } 
    }); 
  Setcontentview (Mlistview); 
    Private View Getheaderview () {TextView Itemview = new TextView (sectionlistview.this); Itemview.setlayoutparams (New Abslistview.layoutparams (VIEWGROup. 
    Layoutparams.match_parent, Msecheight)); 
    Itemview.setgravity (gravity.center_vertical); 
    Itemview.setbackgroundcolor (Color.White); 
    Itemview.settextsize (20); 
    Itemview.settextcolor (Color.gray); 
    Itemview.setbackgroundresource (R.DRAWABLE.SECTION_LISTVIEW_HEADER_BG); 
     
    Itemview.setpadding (0, 0, Itemview.getpaddingbottom ()); 
  return itemview; Private class Listviewadapter extends Baseadapter implements Pinnedheaderadapter {private arraylist< 
    Contact> Mdatas;  
    private static final int type_category_item = 0;  
     
    private static final int type_item = 1; 
    Public Listviewadapter (arraylist<contact> datas) {mdatas = datas; 
    @Override public boolean areallitemsenabled () {return false; @Override public boolean isenabled (int position) {//exception handling if (null = = Mdatas | | positi On < 0| | Position > GetCount ()) {RETUrn true; 
      Contact item = mdatas.get (position); 
      if (item.issection) {return false; 
    return true; 
    @Override public int GetCount () {return mdatas.size (); @Override public int Getitemviewtype (int position) {//exception handling if (null = = Mdatas | | posi tion < 0| | 
      Position > GetCount ()) {return type_item; 
      Contact item = mdatas.get (position); 
      if (item.issection) {return type_category_item; 
    return type_item; 
    @Override public int Getviewtypecount () {return 2; @Override public Object getitem (int position) {return (position >= 0 && Position < MDa Tas.size ())? 
    Mdatas.get (position): 0; 
    @Override public long getitemid (int position) {return 0; @Override public View getview (int positiOn, View Convertview, viewgroup parent) {int itemviewtype = Getitemviewtype (position); 
      Contact data = (Contact) getitem (position); 
       
      TextView Itemview; Switch (itemviewtype) {case type_item:if (null = = Convertview) {Itemview = new TextView (Sect 
          Ionlistview.this); 
          Itemview.setlayoutparams (New Abslistview.layoutparams (ViewGroup.LayoutParams.MATCH_PARENT, mitemheight)); 
          Itemview.settextsize (16); 
          Itemview.setpadding (10, 0, 0, 0); 
          Itemview.setgravity (gravity.center_vertical); 
          Itemview.setbackgroundcolor (Color.argb (255, 20, 20, 20)); 
        Convertview = Itemview; 
        } Itemview = (TextView) Convertview; 
        Itemview.settext (Data.tostring ()); 
         
      Break 
        Case Type_category_item:if (null = = Convertview) {Convertview = Getheaderview (); } Itemview = (TextView) CONVERTVIew; 
        Itemview.settext (Data.tostring ()); 
      Break 
    return convertview; @Override public int getpinnedheaderstate (int position) {if (position < 0) {return Pinn 
      Ed_header_gone; 
      Contact item = (contact) getitem (position); 
      Contact Itemnext = (Contact) getitem (position + 1); 
      Boolean issection = Item.issection; Boolean isnextsection = (null!= itemnext)? 
      ItemNext.isSection:false; 
      if (!issection && isnextsection) {return pinned_header_pushed_up; 
    return pinned_header_visible; @Override public void Configurepinnedheader (View header, int position, int alpha) {Contact item = (C 
      ontact) GetItem (position); 
        if (null!= item) {if (header instanceof TextView) {(TextView) header). SetText (ITEM.SECTIONSTR); 
 } 
      } 
    } 
  } 
}

Finally a screenshot:
above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud-dwelling community.

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.