Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/38238749, this article from: "Zhang Hongyang's Blog"
A buddy of the group is chatting today by chance to mention the controls on this git hub: Pull-to-refresh, interested to see, the examples are extremely powerful and support many controls. This blog details the next listview and the GridView use Pull-to-rerfesh to achieve pull-down refresh and pull-up load more.
1. ListView drop-down refresh Quick Start
Pull-to-refresh to the ListView, called: Pulltorefreshlistview, Usage and the ListView is no different, see the demo below.
Layout file:
<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 " > <com.handmark.pulltorefresh.library.pulltorefreshlistview xmlns:ptr= "/http Schemas.android.com/apk/res-auto " android:id=" @+id/pull_refresh_list " android:layout_width=" Fill_ Parent " android:layout_height=" fill_parent " android:cachecolorhint=" #00000000 " android:divider=" # 19000000 " android:dividerheight=" 4DP " android:fadingedge=" None " android:fastscrollenabled=" False " android:footerdividersenabled=" false " android:headerdividersenabled=" false " Android: Smoothscrollbar= "true" > </com.handmark.pulltorefresh.library.pulltorefreshlistview></ Relativelayout>
Declare a pulltorefreshlistview, all of the properties are ListView, there is no other property, of course, Pulltorefreshlistview also provides a lot of configuration properties, which will be described in detail later.
Activity's Code:
Package Com.example.zhy_pulltorefreash_chenyoca;import Java.util.linkedlist;import Android.app.activity;import Android.os.asynctask;import Android.os.bundle;import Android.text.format.dateutils;import Android.widget.arrayadapter;import Android.widget.listview;import Com.handmark.pulltorefresh.library.pulltorefreshbase;import Com.handmark.pulltorefresh.library.pulltorefreshbase.onrefreshlistener;import Com.handmark.pulltorefresh.library.pulltorefreshlistview;public class Pulltorefreshlistactivity extends Activity{ Private linkedlist<string> mlistitems;/** * pull-up refreshed controls */private Pulltorefreshlistview Mpullrefreshlistview; Private arrayadapter<string> madapter;private int mitemcount = 9; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);// Get Control Mpullrefreshlistview = (Pulltorefreshlistview) Findviewbyid (r.id.pull_refresh_list);//Initialize Data Initdatas ();// Set adapter Madapter = new Arrayadapter<string> (This,anDroid. R.layout.simple_list_item_1, Mlistitems); Mpullrefreshlistview.setadapter (madapter);// Set Listener Event Mpullrefreshlistview.setonrefreshlistener (new Onrefreshlistener<listview> () {@Overridepublic void Onrefresh (pulltorefreshbase<listview> refreshview) {String label = Dateutils.formatdatetime ( Getapplicationcontext (), System.currenttimemillis (), dateutils.format_show_time| dateutils.format_show_date| Dateutils.format_abbrev_all);//Displays the last updated time Refreshview.getloadinglayoutproxy (). Setlastupdatedlabel (label);// Simulate load Task new Getdatatask (). Execute ();});} private void Initdatas () {//Initialize data and data source Mlistitems = new linkedlist<string> (); for (int i = 0; i < Mitemcount; i++) {m Listitems.add ("" + i);}} Private class Getdatatask extends Asynctask<void, void, string>{@Overrideprotected String doinbackground (void ... params) {try{thread.sleep;} catch (Interruptedexception e) {}return "" + (mitemcount++);} @Overrideprotected void OnPostExecute (String result) {Mlistitems.add (result); madapter.notifyDatasetchanged ();//Call Onrefreshcomplete If the list has been Refreshed.mPullRefreshListView.onRefreshComplete ();}}
The code is extremely simple, get the Pulltorefreshlistview control, and set the dataset like a ListView. Of course, we have a pull-down refresh, so we have to set the callback for the dropdown refresh:
Setonrefreshlistener (New Onrefreshlistener<listview> () {}
We simulated an asynchronous task in the callback and loaded an item.
:
Drop down, perform our getdatatask task, call Mpullrefreshlistview.onrefreshcomplete () in OnPostExecute after the task is completed, and complete the refresh.
is not a split-minute implementation of the drop-down refresh. Of course, you may have questions, can I customize the text on the indicator for the drop-down refresh? Can I change the picture to an arrow? Good pull-up load more? The following will be added ~
2. Add pull-up load more
If you want to implement pull-up loading more, you first need to add a property in the Declaration property of the layout file to specify the current drop-down mode:
<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 "> <com. Handmark.pulltorefresh.library.PullToRefreshListView xmlns:ptr= "Http://schemas.android.com/apk/res-auto" and Roid:id= "@+id/pull_refresh_list" android:layout_width= "fill_parent" android:layout_height= "Fill_parent" Android:cachecolorhint= "#00000000" android:divider= "#19000000" android:dividerheight= "4DP" Android : fadingedge= "None" Android:fastscrollenabled= "false" android:footerdividersenabled= "false" Android:he Aderdividersenabled= "false" android:smoothscrollbar= "true" ptr:ptrmode= "both" > </com.handmark.pull Torefresh.library.pulltorefreshlistview></relativelayout>
We have added an attribute: ptr:ptrmode= "Both", meaning: both pull-up and drop-down are supported.
Optional values are: Disabled (disable drop-down refresh), Pullfromstart (only supports pull-down refresh), Pullfromend (pull-up refresh only), both (both supported), MANUALONLY (manual trigger only)
Of course, if you do not like to specify in the layout file, you can completely use the code settings, in OnCreate write: Mpullrefreshlistview.setmode (mode.both);//Set the mode you need
Set the mode to both bidirectional support, of course, you must set the callback for the pull-up and the dropdown, see the following code:
Package Com.example.zhy_pulltorefreash_chenyoca;import Java.util.linkedlist;import Android.app.activity;import Android.os.asynctask;import Android.os.bundle;import Android.text.format.dateutils;import Android.util.Log;import Android.widget.arrayadapter;import Android.widget.listview;import Com.handmark.pulltorefresh.library.pulltorefreshbase;import Com.handmark.pulltorefresh.library.pulltorefreshbase.mode;import Com.handmark.pulltorefresh.library.pulltorefreshbase.onrefreshlistener;import Com.handmark.pulltorefresh.library.pulltorefreshbase.onrefreshlistener2;import Com.handmark.pulltorefresh.library.pulltorefreshlistview;public class Pulltorefreshlistactivity extends Activity{ Private linkedlist<string> mlistitems;/** * pull-up refreshed controls */private Pulltorefreshlistview Mpullrefreshlistview; Private arrayadapter<string> madapter;private int mitemcount = 9; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);//Get control Mpullrefreshlistview = (Pulltorefreshlistview) Findviewbyid (r.id.pull_refresh_list); Mpullrefreshlistview.setmode (Mode.both);//Initialize Data Initdatas ();//Set Adapter Madapter = new Arrayadapter<string> (This, Android. R.layout.simple_list_item_1, Mlistitems); Mpullrefreshlistview.setadapter (Madapter); Mpullrefreshlistview.setonrefreshlistener (New onrefreshlistener2<listview> () {@Overridepublic void Onpulldowntorefresh (pulltorefreshbase<listview> refreshview) {log.e ("TAG", "Onpulldowntorefresh");// Here write down the refresh task of new Getdatatask (). Execute (); @Overridepublic void Onpulluptorefresh (pulltorefreshbase<listview> refreshview) {log.e ("TAG", " Onpulluptorefresh ")///Here write up pull load More tasks New Getdatatask (). Execute ();});} private void Initdatas () {//Initialize data and data source Mlistitems = new linkedlist<string> (); for (int i = 0; i < Mitemcount; i++) {m Listitems.add ("" + i);}} Private class Getdatatask extends Asynctask<void, void, string>{@Overrideprotected String doinbackground (void ... params) {TRY{THREAD.SLEEP (2000);} catch (Interruptedexception e) {}return "" + (mitemcount++);} @Overrideprotected void OnPostExecute (String result) {Mlistitems.add (result); madapter.notifydatasetchanged ();// Call Onrefreshcomplete when the list has been Refreshed.mPullRefreshListView.onRefreshComplete ();}}
And the first paragraph of the code only one place there is a difference, it may be difficult to find:
Mpullrefreshlistview.setonrefreshlistener (New Onrefreshlistener2<listview> () {}); Note that the interface type here is OnRefreshListener2, more than 2, and the above is not the same, this interface contains two methods, a pull-back callback, a drop-down callback. OK, so we've successfully added the pull-up and pull-down, and can control its callback code, respectively.
:
How, is not also very simple ~ Note: If your pull-up and pull-down requirements are executing the same code, then you can continue to register the Onrefreshlistener interface, both the pull-up and the drop-down will perform the same method.
Next, we'll show you how to refresh and load more GridView and custom styles using the drop-down ~
3. GridView with Pull and pull (Pulltorefreshgridview)
The same Pull-to-refresh the GridView package as: Pulltorefreshgridview. Use and pulltorefreshlistview the same ~
First look at the main layout file:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical "&G T <!--the Pulltorefreshgridview replaces a standard GridView widget. --<com.handmark.pulltorefresh.library.pulltorefreshgridview xmlns:ptr= "Http://schemas.android.com/apk/re S-auto "android:id=" @+id/pull_refresh_grid "android:layout_width=" Fill_parent "android:layout_height= "Fill_parent" android:columnwidth= "100DP" android:gravity= "Center_horizontal" Android:horizontalspaci ng= "1DP" android:numcolumns= "Auto_fit" android:stretchmode= "ColumnWidth" android:verticalspacing= "1DP "Ptr:ptrdrawable=" @drawable/ic_launcher "ptr:ptrmode=" both "/></linearlayout>
Pulltorefreshgridview the layout file for the item:
<?xml version= "1.0" encoding= "Utf-8"? ><textview xmlns:android= "http://schemas.android.com/apk/res/ Android " android:id=" @+id/id_grid_item_text " android:layout_width=" 100DP " android:gravity=" center " android:textcolor= "#ffffff" android:textsize= "16sp" android:background= "#000000" android: layout_height= "100DP"/>
The following is the code for the activity:
public class Pulltorefreshgridactivity extends Activity{private linkedlist<string> mlistitems;private Pulltorefreshgridview mpullrefreshlistview;private arrayadapter<string> mAdapter;private int mItemCount = 10;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_ptr_grid);//Get control Mpullrefreshlistview = (Pulltorefreshgridview) Findviewbyid (R.id.pull_refresh_ grid);//Initialize data and data source Initdatas (); madapter = new Arrayadapter<string> (This, r.layout.grid_item,r.id.id_grid_item_ text, mlistitems); Mpullrefreshlistview.setadapter (Madapter); Mpullrefreshlistview.setonrefreshlistener (new Onrefreshlistener2<gridview> () {@Overridepublic void Onpulldowntorefresh (pulltorefreshbase<gridview> Refreshview) {log.e ("TAG", "Onpulldowntorefresh");//do work toString label = Dateutils.formatdatetime ( Getapplicationcontext (), System.currenttimemillis (), dateutils.format_show_time| dateutils.format_show_date| Dateutils.fOrmat_abbrev_all);//Update the Lastupdatedlabelrefreshview.getloadinglayoutproxy (). Setlastupdatedlabel (label); New Getdatatask (). Execute ();} @Overridepublic void Onpulluptorefresh (pulltorefreshbase<gridview> refreshview) {log.e ("TAG", " Onpulluptorefresh "); Do work to refresh//the list here.new getdatatask (). Execute ();}); private void Initdatas () {mlistitems = new linkedlist<string> (); for (int i = 0; i < Mitemcount; i++) {Mlistitems.ad D (i + "");}} Private class Getdatatask extends Asynctask<void, void, void>{@Overrideprotected void Doinbackground (void ... params) {try{thread.sleep;} catch (Interruptedexception e) {}return null;} @Overrideprotected void OnPostExecute (void result) {Mlistitems.add ("" + mitemcount++); Madapter.notifydatasetchanged ( );//Call Onrefreshcomplete when the list has been Refreshed.mPullRefreshListView.onRefreshComplete ();}}
Basically the above example does not have any difference, see directly:
The effect is good, if you are more careful will find that the pull-up of the spinning of the picture into a robot, that is because I set up in the layout file:
<com.handmark.pulltorefresh.library.pulltorefreshgridview ptr:ptrdrawable= "@drawable/ic_launcher" ... />
Of course, this is the effect of rotation, commonly used also, an arrow inverted effect, in fact, is also very simple, a property:
ptr:ptranimationstyle= "Flip"
Remove the ptr:ptrdrawable= "@drawable/ic_launcher" property, and if you want to use the default arrow, you can also customize it.
Once added, the arrows look like this:
Ptr:ptranimationstyle value: Flip (flip animation), rotate (rotate animation).
The ptr:ptrdrawable is the set icon.
4, custom drop-down indicator text content and other effects
A Iloadinglayout object can be obtained by mpullrefreshlistview.getloadinglayoutproxy () after initialization completes Mpullrefreshlistview. This object can set styles, text, and so on in various indicators.
Iloadinglayout startlabels = Mpullrefreshlistview.getloadinglayoutproxy (); Startlabels.setpulllabel ("You can pull, pull ..."); /Just drop-down, the prompt Startlabels.setrefreshinglabel ("OK, is refreshing ...");//Refresh when Startlabels.setreleaselabel ("You dare to put, I dare to refresh ...");// When it reaches a certain distance, the displayed hints
If you are more careful, you will find that we set the last refresh time in front of the use of:
Update the Lastupdatedlabel
Refreshview.getloadinglayoutproxy (). Setlastupdatedlabel (label);
Now the effect is:
The default is pull-up and drop-down words change at the same time, if I want to change it individually?
private void Initindicator () {Iloadinglayout startlabels = Mpullrefreshlistview.getloadinglayoutproxy (True, false); Startlabels.setpulllabel ("You can pull, pull ...");//Just pull down, show the hint Startlabels.setrefreshinglabel ("OK, is refreshing ...");// Refresh when Startlabels.setreleaselabel ("You dare to put, I dare to refresh ...");//down to a certain distance, show the hint iloadinglayout endlabels = Mpullrefreshlistview.getloadinglayoutproxy (False, True); Endlabels.setpulllabel ("You can pull, pull 2 ...");//Just pull down, The prompt displayed Endlabels.setrefreshinglabel ("OK, refreshing 2 ...");//Refresh Endlabels.setreleaselabel ("You dare to put, I will dare to refresh 2 ...");//down to a certain distance, Prompt to display}
Mpullrefreshlistview.getloadinglayoutproxy (True, false), receives two parameters, sets the drop-down iloadinglayout for True,false, and false to True returns the setting of the pull-up.
5, some of the commonly used properties
Of course, Pull-to-refresh can also define some properties in XML:
Ptrmode,ptrdrawable,ptranimationstyle These three have been described above.
Ptrrefreshableviewbackground setting the background color of the entire Mpullrefreshlistview
Ptrheaderbackground setting the background color of the dropdown header or pull-up footer
Ptrheadertextcolor used to set the color of the header and footer Chinese text
Ptrheadersubtextcolor used to set the color of the last refresh time in the header and footer
Ptrshowindicator If True will appear in the Mpullrefreshlistview icon, the upper right corner and the lower right corner, it is very interesting.
Ptrheadertextappearance, ptrsubheadertextappearance respectively sets the type color of the font in the header or pull-up footer, and so on.
Ptrrotatedrawablewhilepulling whether the drop is rotated when the animation is set to rotate.
Ptrscrollingwhilerefreshingenabled whether the ListView or GridView is allowed to scroll when refreshed. Think it's better to be true.
Ptrlistviewextrasenabled determines the way Header,footer joins Mpullrefreshlistview,true for Headview, that is, the refresh head scrolls together when scrolling.
The last 2 in fact for the user experience is very important, if you set the time to consider the next ~. other attributes are just as good as their choice.
Note: Many of the above properties can be code-controlled, if necessary, can be directly Mpullrefreshlistview.set property name view
The above are all supported attributes of Pull-to-refresh ~ ~
Defines a bunch of effects:
The icon on the top right and bottom right is ptrshowindicator. Well, you can explain the configuration to the above attributes according to your own needs.
The example downloaded on GitHub is dependent on 3 items, a basic Library_pulltorefresh, a pulltorefreshviewpager, a pulltorefreshlistfragment;
The example described above relies only on Library_pulltorefresh, and the other two dependencies do not have to be imported.
Well, if you think this blog is useful to you, just leave a message.
SOURCE Click to download