Android ListView Paging Load Data function implementation code _android

Source: Internet
Author: User

What is the ListView paging load Data feature? In today's big data age, it's impossible to show some of the data to the interface, like we often see the QQ space, when you look at the dynamic, the system will not be all the friends of the dynamic display on the above, you can see the general is the latest update friends, if you want to see not the latest friend dynamic, Usually you swipe your fingers up and down the screen and check when the interface down to a certain number of times, you will see a "view more", and then suddenly paused, the system will be through the network to refresh you other dynamic information, such functions we generally call the data Drop-down refresh function, that is, our paging load function, What is the specific implementation? Now let's start with a detailed explanation.

the principle of implementation:
1. First of all, to determine the default display on the ListView data, such as the default on the ListView display 10 data.
2. Pass the data to the custom adapter and load into the ListView.
3. When the user pulls the data to the last one, it's time to start refreshing and loading the new data.
4. By listening to the ListView sliding events, to determine whether the last one, if the last one to start refreshing.

Detailed implementation steps are explained in detail in the code.

The overall structure is as follows:

Activity_main.xml

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android=
"http://schemas.android.com/apk" /res/android "
  xmlns:tools=" Http://schemas.android.com/tools "
  android:layout_width=" Match_parent
  " android:layout_height= "Match_parent"
  tools:context= "com.company.listviewdeepknow.MainActivity" >

  <listview
    android:id= "@+id/mlist"
    android:layout_width= "Match_parent"
    Match_parent ">
  </ListView>
</RelativeLayout>

Foot_boot.xml

<?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=" 70DP "
  android:gravity=" Center "
  android:orientation=" Horizontal ">

  <progressbar
    android:id=" @+id/progressbar
    " Style= "Android:attr/progressbarstylesmall"
    android:layout_width= "45DP"
    android:layout_height= "45DP"/ >

  <textview
    android:id= "@+id/mload"
    android:layout_width= "Wrap_content"
    android: layout_height= "Wrap_content"
    android:text= "load more ..."
    android:textsize= "20sp"/> </
Linearlayout>

List_item.xml

<?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 "
  android:o" rientation= "Horizontal" >

  <textview
    android:id= "@+id/mtv1"
    android:layout_width= "100DP"
    android:layout_height= "100DP"
    android:textsize= "20sp"/>

  <textview
    android:id= "@+id/mtv2"
    android:layout_width= "100DP"
    android:layout_height= "100DP"
    android:layout_alignparentright= " True "
    android:textsize= 20sp"/>
</RelativeLayout>

Mainactivity.java

Data displayed by public class Mainactivity extends Appcompatactivity implements Myonscrolllistener.onloaddatalistener {//listview
  Item private list<student> data;

  ListView control private ListView mlist;

  Custom adapter Myadapter Adapter;

  Bottom load more layout View footer;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    The default data is loaded first, set to 10 getData ();
    Display to ListView on Showlistview (data);
    Custom scrolling Listener Event Myonscrolllistener Onscrolllistener = new Myonscrolllistener (footer, data);
    Set interface callback Onscrolllistener.setonloaddatalistener (this);
  Set up the ListView Rolling Listener Event Mlist.setonscrolllistener (Onscrolllistener);
    /** * Initializes the ListView data, the default setting is 10/private void GetData () {data = new arraylist<> ();
    Student stu = null;
      for (int i = 0; i < i++) {stu = new Student ();
      Stu.setname ("name" + i); Stu.setsex (i% 2 = 0?)
   "Male": "female");   Data.add (Stu);
    }/** * Loads data onto ListView * * @param/private void Showlistview (list<student> data) { First to determine if the adapter is empty, the first run is definitely empty if (adapter = = NULL) {//Check the ListView control mlist = (ListView) Findviewbyid (r.id.mlist)
      ;
      Load the bottom one load more layout footer = Layoutinflater.from (this). Inflate (r.layout.foot_boot, NULL);
      The initial state is hidden footer.setvisibility (view.gone);
      Add to the bottom of the ListView Mlist.addfooterview (footer);
      Create Adpter adapter = new Myadapter (data);
    Setting adapter Mlist.setadapter (adapter);
      else {//not empty, refresh data This.data =;
    Remind ListView to update the data adapter.notifydatasetchanged (); }} @Override public void Onloaddata (list<student> data) {//loading is complete, display data to ListView Showlistview
  );

 }
}

Myonscrolllistener.java

public class Myonscrolllistener implements Abslistview.onscrolllistener {//listview total number of private int Totalitemcou

  nt

  ListView the last item item private int lastitem;

  Used to determine whether a private Boolean isloading is currently loaded;

  Bottom load more layout private View footer;

  An instance of an interface callback private Onloaddatalistener listener;

  Data private list<student>;
    Public Myonscrolllistener (View footer, list<student> data) {this.footer = footer;
  This.data = data;
  }//Set instance of interface callback public void Setonloaddatalistener (Onloaddatalistener listener) {This.listener = listener; /** * Sliding State change * @param view * @param scrollstate 1 Scroll_state_touch_scroll is dragging 2 scroll_state_fling is inertia The sliding 0scroll_state_idle is stopped and will only be performed when switching between different states/@Override public void onscrollstatechanged (Abslistview view, int s  Crollstate) {//If the data is not loaded and the sliding state is stopped, and the last item item is reached if (!isloading && lastitem = = Totalitemcount && Scrollstate = = Scroll_state_idle) {//display PlusCarrying more footer.setvisibility (view.visible);
      Handler Handler = new Handler (); Simulate a refresh feature with a delay of two seconds handler.postdelayed (new Runnable () {@Override public void run () {if (LIS
            Tener!= null) {//Start loading more data loadmoredata ();
            The callback sets the ListView data listener.onloaddata;
          What LoadComplete () to operate after loading is completed;
    }}, 2000); }/** * When the load data is complete, setting the load flag to False indicates that no data has been loaded * and set the bottom load more for hidden */private void LoadComplete () {isloading =
    False

  Footer.setvisibility (View.gone);
    /** * Start loading more new data, here update only three data per time * * private void Loadmoredata () {isloading = true;
    Student stu = null;
      for (int i = 0; i < 3; i++) {stu = new Student ();
      Stu.setname ("New name" + i);
      Stu.setsex ("New sex" + i);
    Data.add (Stu); }/** * Monitor visible interface * @param view ListView * @param the index of the first visible item * @paRam VisibleItemCount can display the number of item * @param totalitemcount Total number of item */@Override public void onscroll (Abslis Tview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {//when the visible interface of the first item + the current interface more than the number of visible interface can get the last
    Item Item has LastItem = Firstvisibleitem + visibleitemcount;
  The total listview Item Number This.totalitemcount = Totalitemcount;
  }//Callback interface public interface Onloaddatalistener {void Onloaddata (list<student> data);

 }
}

Myadapter.java

public class Myadapter extends mybaseadapter<student> {public

  myadapter (list<student> data) {
    Super (data);
  }

  @Override public
  void SetData (Viewholder holder, Student t) {
    holder.settext (R.ID.MTV1, T.getname ()). SetText ( R.ID.MTV2, T.getsex ());

  }



Mybaseadapter.java

Public abstract class Mybaseadapter<t> extends Baseadapter {
  protected list<t> data;
  Public Mybaseadapter (list<t> data) {
    this.data = data;
  }
  @Override public
  int GetCount () {return
    data = null 0:data.size ();
  }

  @Override public
  Object getitem (int position) {return
    data.get (position);
  }

  @Override public
  long getitemid (int position) {return
    position;
  }

  @Override public
  View getview (int position, View Convertview, ViewGroup parent) {
    Viewholder holder = Viewholde R.getholder (Convertview,parent,position, r.layout.list_item);
    SetData (Holder,data.get (position));
    return Holder.getconvertview ();
  }
  public abstract void SetData (Viewholder holder,t T);
}

Viewholder.java

public class Viewholder {private int position;
  Private sparsearray<view> Array;
  Private View Convertview;

  private context;
    Private Viewholder (viewgroup parent, int position, int layout) {this.position = position;
    This.context = Parent.getcontext ();
    Convertview = Layoutinflater.from (Parent.getcontext ()). Inflate (layout, null);
    Convertview.settag (this);
  Array = new sparsearray<> (); public static Viewholder Getholder (View Convertview, viewgroup parent, int position, int layout) {if (Convertvie
    W = = null) {return new Viewholder (parent, position, layout);
      else {Viewholder holder = (viewholder) convertview.gettag ();
      Holder.position = position;
    return holder;
    } public <t extends view> T getview (int viewid) {View view = Array.get (Viewid);
      if (view = = null) {view = Convertview.findviewbyid (Viewid);
    Array.put (Viewid, view);
  Return (T) view; } publiC View Getconvertview () {return convertview;
    Public Viewholder setText (int viewid, String data) {TextView TV = GetView (Viewid);
    Tv.settext (data);
  return this;

 }

Student.java

public class Student {
  private String name;
  Private String sex;

  Public String GetName () {return
    name;
  }

  public void SetName (String name) {
    this.name = name;
  }

  Public String Getsex () {return
    sex;
  }

  public void Setsex (String sex) {
    this.sex = sex;
  }
}

In addition to Myadapter.java Mybaseadapter.java Viewholder.java and The Student.java entity class has no annotations, and the other two main implementation classes have been commented, and for the explanation of the custom generic adapter, this article does not explain, if you want to know how to implement custom universal adapter knowledge can be viewed:

Here's a look at the effect chart:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.