Using ListView in Android to implement paging refresh (thread sleep simulation), androidlistview

Source: Internet
Author: User

Using ListView in Android to implement paging refresh (thread sleep simulation), androidlistview

When there are too many data to be displayed, in order to better improve user awareness, the display will be refreshed by page in many apps, such as browsing news, when sliding down to the last item of the current ListView, a message is prompted to refresh and load the updated content. This process is roughly divided into the following steps:

1. Current Activity implements OnScallListenner;

2. Interface implementation methods;

3. Register a rolling listener for ListView;

4. the Adapter (custom or Android) fills in data for each item;

5. After obtaining data from the second page, adater adds data and refreshes yydatesetchanged (); (Handler is required)

Now we can simulate the implementation of ListView page refresh by means of thread sleep (10 pieces of information are loaded each time, sliding down will refresh and load by page)

Display Effect (enable Refresh after setting to display ten items, and add an AlertDialog browsing example ):

In Layout, the Layout of ListView is activity_main.xml:

 1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout 3     xmlns:android="http://schemas.android.com/apk/res/android" 4     xmlns:tools="http://schemas.android.com/tools" 5     android:id="@+id/activity_main" 6     android:layout_width="match_parent" 7     android:layout_height="match_parent" 8     tools:context="com.example.administrator.day08.MainActivity"> 9     <ListView10         android:id="@+id/lv"11         android:layout_width="match_parent"12         android:layout_height="match_parent"13         android:layout_alignParentTop="true"14         android:layout_alignParentStart="true" />15 </RelativeLayout>

In Layout, the Layout of item. xml file is as follows:

 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     android:orientation="vertical" android:layout_width="match_parent" 4     android:layout_height="match_parent"> 5     <TextView 6         android:text="Tile" 7         android:textSize="30dp" 8         android:layout_width="match_parent" 9         android:layout_height="wrap_content"10         android:id="@+id/textView" />11     <TextView12         android:text="Message"13         android:textSize="20dp"14         android:layout_width="match_parent"15         android:layout_height="wrap_content"16         android:id="@+id/textView2" />17 </LinearLayout>

The Layout (footer) login_item.xml file is refreshed on the page in Layout:

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" 3 android: orientation = "horizontal" android: layout_width = "match_parent" 4 android: layout_height = "match_parent" android: gravity = "center"> 5 <ProgressBar 6> 7 android: layout_width = "wrap_content" 8 android: layout_height = "wrap_content" 9 android: layout_gravity = "center" 10 android: id = "@ + id/progressBar"/> 11 <TextView12 android: text = "loading" 13 android: layout_width = "wrap_content" 14 android: layout_height = "wrap_content" 15 android: id = "@ + id/textView3"/> 16 </LinearLayout>

Custom object classes in Java (each piece of news has a corresponding title and content)

 

1 public class News {2     String title;3     String message;4 }

 

Java function implementation class (by implementing the OnScrollListener Interface)

 

1 import android. content. dialogInterface; 2 import android. OS. handler; 3 import android. OS. message; 4 import android. support. v7.app. alertDialog; 5 import android. support. v7.app. appCompatActivity; 6 import android. OS. bundle; 7 import android. view. view; 8 import android. view. viewGroup; 9 import android. widget. absListView; 10 import android. widget. adapterView; 11 import android. widget. baseAdapter; 12 Import android. widget. listView; 13 import android. widget. textView; 14 import java. util. arrayList; 15 import java. util. list; 16/** 17 * Created by panchengjia on 2016/11/29. 18 */19 public class MainActivity extends AppCompatActivity implements AbsListView. onScrollListener {20 private ListView lv; 21 private List <News> news; // declares List 22 private int total = 1 that stores News titles and content; // The counter (which starts from 1 by default) is used for data initialization in the set. 23 My Adapter adapter; 24 @ Override 25 protected void onCreate (Bundle savedInstanceState) {26 super. onCreate (savedInstanceState); 27 setContentView (R. layout. activity_main); 28 lv = (ListView) findViewById (R. id. lv); 29 // set the OnScrollListener for the current ListView to refresh the page by 30 lv. setOnScrollListener (this); 31 // declare login_item (the item with the pull-down refresh effect) through the layout filler 32 View v = getLayoutInflater (). inflate (R. layout. login_item, null); 33 // set logi N_item is set to ListView footer 34 lv. addFooterView (v); 35 // List 36 news = new ArrayList of instantiated storage content resources <> (); 37 // call the Method 38 initList () to initialize the List (); 39 adapter = new MyAdapter (); 40 // set the event 41 lv for clicking item. setOnItemClickListener (new AdapterView. onItemClickListener () {42 @ Override 43 public void onItemClick (AdapterView <?> Parent, View view, int position, long id) {44 show (view); // event processing is to call the show method (show AlertDialog dialog box) 45} 46}); 47 lv. setAdapter (adapter); 48} 49 // The Call of the AlertDialog dialog box is not described here. In the early stage, a special blog post explains 50 public void show (View v) {51 AlertDialog. builder builder = new AlertDialog. builder (this); 52 TextView title = (TextView) v. findViewById (R. id. textView); 53 TextView message = (TextView) v. findViewById (R. id. textView2); 54 Builder. setTitle (title. getText (). toString (); 55 builder. setMessage (message. getText (). toString (); 56 builder. setPositiveButton ("browsed", new DialogInterface. onClickListener () {57 @ Override 58 public void onClick (DialogInterface dialog, int which) {59 60} 61}); 62 builder. show (); 63} 64 // initialize the elements in the List, simulate refreshing 10 messages each time 65 private void initList () {66 for (int I = 1; I <= 10; I ++) {67 News n = new News (); 68 // Add total because total will not continue from the beginning after refreshing the page. title = "Title --" + total; 70 n. message = "Message" + total; 71 news. add (n); 72 total ++; 73} 74} 75 // int currenVisibleItemCount; // declare the total number of items (used for demonstration) as of the current page 76 boolean isLastRow = false; // determine whether the last item in ListView is 77 @ Override 78 public void onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {79 // firstVisibleItem: the first visible page in Arrayl Subscript in ist, visibleItemCount is the number of items on the current page 80 // items = firstVisibleItem + visibleItemCount-1 = totalItemCount; (DEMO) 81 if (firstVisibleItem + visibleItemCount = totalItemCount & totalItemCount> 0) {82 isLastRow = true; // judge whether the last item (that is, footerView) is reached 83} 84} 85 @ Override 86 public void onScrollStateChanged (AbsListView view, int scrollState) {87/* before judging whether to refresh the page, explain the three states of scrollState 88*1. scrollState = SCROLL_STATE_TOUCH_SCROLL: Press and hold the finger to scroll the screen (not out of the screen); 89*2. scrollState = SCROLL_STATE_FLING can be understood as the slide before the finger leaves the screen. After 90 * fingers exit, the page is still rolling; 91*3. scrollState = SCROLL_STATE_IDLE: the screen is not touched by the finger, and the screen page remains static 92 * Before enabling the line refresh page, make sure that the ListView has reached the last line (Item) and the screen page remains static 93 **/94 if (isLastRow & scrollState = SCROLL_STATE_IDLE) {95 new Thread (new MyThread ()). start (); 96} 97} 98 // create a paging refresh thread (simulated refresh) 99 class MyThread implements Runnable {100 101 @ Override102 public void run () {103 try {104 Thread. sleep (500); // set the thread sleep time to 500 milliseconds to refresh once. 105} catch (InterruptedException e) {106 e. printStackTrace (); 107} 108 initList (); // reinitialize List109 // call Handler within the thread to execute page refresh (the following will write a detailed analysis of handler) 110 handler. sendEmptyMessage (1); 111} 112} 113 Handler handler = new Handler () {114 @ Override115 public void handleMessage (Message msg) {116 super. handleMessage (msg); 117 switch (Msg. what) {118 case // force call the getView of the adapter to refresh the content of each Item. 120 adapter. notifyDataSetChanged (); 121 break; 122} 123} 124}; 125 // custom adapter 126 class MyAdapter extends BaseAdapter {127 @ Override128 public int getCount () {129 return news. size (); 130} 131 @ Override132 public Object getItem (int position) {133 return news. get (position); 134} 135 @ Override136 public long getItemId (int position) {137 return position; 138} 139 @ Override140 public View getView (int position, View convertView, ViewGroup parent) {141 ViewHolder VL; 142 if (convertView = null) {143 convertView = getLayoutInflater (). inflate (R. layout. item, null); 144 Ku = new ViewHolder (); 145 Ku. message = (TextView) convertView. findViewById (R. id. textView2); 146 consecutive seconds. title = (TextView) convertView. findViewById (R. id. textView); 147 convertView. setTag (vh); 148} 149 VL = (ViewHolder) convertView. getTag (); 150 consecutive seconds. title. setText (news. get (position ). title); 151. message. setText (news. get (position ). message); 152 return convertView; 153} 154 class ViewHolder {155 TextView title; 156 TextView message; 157} 158} 159}

 

At this point, the page refresh source code of ListView has been fully displayed. I personally think that the core of implementing this function is to determine whether it has reached the last item in the current ListView (including the footer refresh prompt) and understand the status of scrollState, after understanding these two points, this function is more efficient.

 

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.