Android uses Pulltorefresh to complete ListView drop-down refresh and left-sliding removal features _android

Source: Internet
Author: User
Tags abs gety touch

ListView Refresh Brush function believe that the ape friends who are engaged in Android development are not unfamiliar, including now Google Pro son swiperefreshlayout implementation in some apps can also be seen (but individuals do not like the official refresh effect). This article will lead some new Android friends or friends who love sharing to simple implementation of ListView Drop-down and left-sliding delete effect.

First, the main contents of this article:

Use Pulltorefresh to finish ListView, pull up and refresh;
Extended Pulltorefresh Perfect implementation of ListView left-sliding Delete effect; note: The Pulltorefresh in this article is not a complete open source library, and individuals have removed some unwanted peace-related classes. It looks more streamlined and easier to understand.
Attached Pulltorefresh Source Library download Address: http://download.csdn.net/detail/jaynm/9670737

Second, first look at the effect:

1.ListView Drop-down Refresh, pull up load more:

2.ListView drop-down Refresh, pull load more, left-sliding Delete:

Third, the implementation code:

1. Implement ListView Drop-down Refresh:

As for the Pulltorefreshbase class, their own modified source code, too long here is not posted, you can download demo yourself carefully read, mainly to see how to apply to their own projects:

* Created by Caobo on 2016/11/1 0001. * ListView Drop-down Refresh, Pull load More * * public class Listviewactivity extends activity implements pulltorefreshbase.onrefreshlistener& Lt listview> {private Pulltorefreshlistview refreshlistview; private ListView Mlistview;//Add Data list collection//
TODO: Here you use the LinkedList to add data to your demo and use ArrayList in your actual project.
Private linkedlist<string> PullData;
Private ListAdapter adapter;
Mark dropdown index private int pulldownindex = 0;
Tag pull index private int pullupindex = 0; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_listview);
PullData = new linkedlist<> ();
Refreshlistview = (Pulltorefreshlistview) Findviewbyid (R.id.refreshlistview);
Refreshlistview.setpullloadenabled (FALSE);
Refreshlistview.setscrollloadenabled (TRUE);
Refreshlistview.setonrefreshlistener (this);
Mlistview = Refreshlistview.getrefreshableview ();
adapter = new ListAdapter (GetData ());
Mlistview.setadapter (adapter); Refreshlistview.Onrefreshcomplete ();
@Override public void Onpulldowntorefresh (pulltorefreshbase<listview> refreshview) {Onpulldown ();} @Override 
public void Onpulluptorefresh (pulltorefreshbase<listview> refreshview) {Onpullup ();}/** * Pre-loading initialization data list * @return * * Public list<string> GetData () {for (int i = 1; I <= i++) {pulldata.add ("Default ListView data" + i);} return PU
Lldata; /** * Drop-down Refresh Add data to list set/public void Onpulldown () {Pulldata.addfirst ("dropdown Refresh data" + Pulldownindex); pulldownindex++
Hlistview.onrefreshcomplete ();
Adapter.notifydatasetchanged (); /** * Pull load Add data to list set/public void Onpullup () {pulldata.addlast ("Pull load data" + Pullupindex); pullupindex++
Ew.onrefreshcomplete ();
Adapter.notifydatasetchanged (); public void Onbackclick (view view) {Finish ();}}

is not the above operation or very simple to complete the ListView Drop-down Refresh, pull load more.

The XML layout file is also simple enough to refer to the Pulltorefreshlistview address:

So we're done with a listview list of Drop-down refreshes and pull loads more, and personally think Pulltorefresh this library is still very powerful.

<?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=" match_parent "
android:o" rientation= "vertical" >
<com.jaynm.pulltorefreshscrollviewdemo.refresh.pulltorefreshlistview
Android:background= "#000"
android:id= "@+id/refreshlistview"
android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
android:cachecolorhint= "@android: Color/transparent"
android: divider= "@color/consumer_bg"
android:dividerheight= "1px"
android:fadingedge= "None"
android:o rientation= "vertical"
android:overscrollmode= "never"
android:requiresfadingedge= "None" >
< /com.jaynm.pulltorefreshscrollviewdemo.refresh.pulltorefreshlistview>
</LinearLayout>

1. Implement ListView Drop-down Refresh, left-sliding Delete:

Attention:

A. Rewrite listview here to generate Swipemenulistview, so he is still a ListView list control;

B. Since the need for left-slip, it must be in the Ontouchevent () method to determine the operation of gesture sliding;

C. The need to take into account the conflict of the dropdown, pull and left-slip events;

D. The need to consider a left-sliding delete event can only have one item in the deletion state at a time;

@Override public boolean ontouchevent (motionevent ev) {if ev.getaction ()!= motionevent.action_down && Mtouchvi
EW = NULL) return super.ontouchevent (EV);
int action = Ev.getaction (); Switch (action) {case MotionEvent.ACTION_DOWN:int oldpos = mtouchposition; mdownx = Ev.getx (); mdowny = Ev.gety (); Mtouc
Hstate = Touch_state_none;
Mtouchposition = pointtoposition ((int) ev.getx (), (int) ev.gety ());
if (mtouchposition = = Oldpos && mtouchview!= null && mtouchview.isopen ()) {mtouchstate = touch_state_x;
Mtouchview.onswipe (EV);
return true;
View view = Getchildat (Mtouchposition-getfirstvisibleposition ()); if (Mtouchview!= null && mtouchview.isopen ()) {Mtouchview.smoothclosemenu (); mtouchview = null;//Return super.
Ontouchevent (EV);
Try to cancel the touch event motionevent CancelEvent = Motionevent.obtain (EV);
Cancelevent.setaction (Motionevent.action_cancel);
Ontouchevent (CancelEvent); if (Monmenustatechangelistener!= null) {MonmenustatechangeListener.onmenuclose (Oldpos);
return true; 
} if (view instanceof swipemenulayout) {Mtouchview = (swipemenulayout) view; mtouchview.setswipedirection (mDirection);}
if (Mtouchview!= null) {mtouchview.onswipe (EV); Case Motionevent.action_move://Some may have header, subtract header and then judge mtouchposition = pointtoposition ((int) ev.getx (), (int)
Ev.gety ())-Getheaderviewscount (); If the slide is not fully displayed, take it back, this time Mtouchview has been assigned, and then slide another SWIP view//will lead to Mtouchview Swip. So to use position to determine whether the slide is a view if (!mtouchview.getswipenable () | | | mtouchposition!= mtouchview.getposition ()) {break;} float dy =
Math.Abs ((Ev.gety ()-mdowny));
float dx = Math.Abs ((Ev.getx ()-mdownx)); if (mtouchstate = = touch_state_x) {if (Mtouchview!= null) {mtouchview.onswipe (EV);} getselector (). SetState (New int[]{0
});
Ev.setaction (Motionevent.action_cancel);
Super.ontouchevent (EV);
return true; else if (mtouchstate = = Touch_state_none) {if math.abs (dy) > max_y) {mtouchstate = touch_state_y;} else if (dx &G T max_x) {MtouchstaTe = touch_state_x;
if (Monswipelistener!= null) {Monswipelistener.onswipestart (mtouchposition);}}
} break; Case MotionEvent.ACTION_UP:if (mtouchstate = = touch_state_x) {if (Mtouchview!= null) {Boolean isbeforeopen = Mtouchvie
W.isopen ();
Mtouchview.onswipe (EV);
Boolean isafteropen = Mtouchview.isopen (); if (isbeforeopen!= isafteropen && monmenustatechangelistener!= null) {if (Isafteropen) {monmenustatechangelist
Ener.onmenuopen (mtouchposition);
else {monmenustatechangelistener.onmenuclose (mtouchposition);}}
if (!isafteropen) {mtouchposition =-1; mtouchview = null;}} if (Monswipelistener!= null) {monswipelistener.onswipeend (mtouchposition);} ev.setaction (Motionevent.action_cancel
);
Super.ontouchevent (EV);
return true;
} break;
return super.ontouchevent (EV); }

Monswipelistener.onswipestart (mtouchposition), used to record the mark where the current gesture status is Motionevent.action_move to the left and slide. Monswipelistener.onswipeend (mtouchposition) used to record the mark when the current gesture status is motionevent.action_up to the left This is primarily used to get the current operating state when the activity interface callback is done, so we can solve the third problem above with the Onswipestart () and Onswipeend () two callback methods (need to take into account the conflicts of dropdown, pull, and left-sliding events)

Operation ListView left-hand gesture operation, which is used to deal with the sliding up and down the conflict: when the beginning of the slide, it is forbidden to pull down and pull the gesture operation, the end of the sliding back to pull back and down operation
Swipemenulistview.setonswipelistener (New Swipemenulistview.onswipelistener () {
@Override public
Void Onswipestart (int position) {
refreshlistview.setpullrefreshenabled (false);
}
@Override public
void onswipeend (int position) {
refreshlistview.setpullrefreshenabled (true);
}
});

Refreshlistview.setpullrefreshenabled (false); The method is that I have customized in the Pulltorefreshbase whether to support the Drop-down refresh operation event, we can according to Onswipestart () and the Onswipeend () method to set it up.

In this way we have solved the above three points of attention, so as to achieve ListView left-slip Delete is also a very easy thing.

Here's what it looks like. D, this needs to be done in the event distribution mechanism: Because when we left the Itema Delete button, again to slide itemb, can not let it also appear, we have to close off the Itema delete state, this is the reasonable operation, So in the method to handle the blocking event:

@ public boolean onintercepttouchevent (motionevent ev) {//processing at intercept, also can SWIP when sliding set click event, click Can not affect the original click event int action = Ev.ge
Taction (); Switch (action) {Case MotionEvent.ACTION_DOWN:mDownX = Ev.getx (); mdowny = Ev.gety (); Boolean handled = Super.onintercep
Ttouchevent (EV);
Mtouchstate = Touch_state_none;
Mtouchposition = pointtoposition ((int) ev.getx (), (int) ev.gety ());
View view = Getchildat (Mtouchposition-getfirstvisibleposition ()); Assign values only when they are empty to prevent each touch from being assigned, there will be more than one open state if (view instanceof swipemenulayout) {//If one is open, intercept. if (Mtouchview!= null && mTo Uchview.isopen () &&!inrangeofview (Mtouchview.getmenuview (), Ev)) {return true;} Mtouchview = (swipemenulayout
) view;
Mtouchview.setswipedirection (mdirection); //If you touch another view if (Mtouchview!= null && mtouchview.isopen () && view!= mtouchview) {handled = true;} I
F (mtouchview!= null) {mtouchview.onswipe (EV);} return handled;
Case MotionEvent.ACTION_MOVE:float dy = Math.Abs (ev.gety ()-mdowny)); Float Dx = Math.Abs ((Ev.getx ()-mdownx)); if (Math.Abs (dy) > Max_y | | Math.Abs (dx) > max_x) {//The touch state is set at the down of each intercept touch_state_none only return true to go ontouchevent so write here is enough if (mtouchstate = Touch_state_none) {if (Math.Abs (dy) > max_y) {mtouchstate = touch_state_y;} else if (dx > max_x) {mtouchstate =
touch_state_x;
if (Monswipelistener!= null) {Monswipelistener.onswipestart (mtouchposition);}}
return true;
} return super.onintercepttouchevent (EV); }

OK, the above is all the event handling code in the Swipemenulistview class, the following can be used to reference our definition of swipemenulistview, so that the ListView Drop-down refresh, pull load, left sliding delete effect.

Create a left-sliding pop-up item Swipemenucreator creator = new Swipemenucreator () {@Override public void Create (Swipemenu menu) {//create it
EM swipemenuitem openitem = new Swipemenuitem (Getapplicationcontext ());
Sets the background color of the item openitem.setbackground (new Colordrawable (color.red));
Sets the width of the item openitem.setwidth (UTILS.DIP2PX (swipelistviewactivity.this,90));
Set Item title openitem.settitle ("delete");
Set the item font size openitem.settitlesize (18);
Sets the item font color Openitem.settitlecolor (color.white);
Add to ListView's item Layout Menu.addmenuitem (Openitem);
}
};
Set creator Swipemenulistview.setmenucreator (creator); Action Delete button click event Swipemenulistview.setonmenuitemclicklistener (New Swipemenulistview.onmenuitemclicklistener () {@ Override public boolean onmenuitemclick (final int position, swipemenu menu, int index) {toast.maketext (swipelistviewacti
Vity.this, "delete" +pulldata.get (position), Toast.length_long). Show ();
return false;
}
}); Operation ListView left-hand gesture operation, which is used to deal with the sliding up and down the conflict: when the start of the slide, it is forbidden to pull and pull the gesture operation, the end of the sliding back and back pull operation Swipemenulistview.setonswipelIstener (New Swipemenulistview.onswipelistener () {@Override public void Onswipestart (int position) {
Refreshlistview.setpullrefreshenabled (FALSE);
@Override public void onswipeend (int position) {refreshlistview.setpullrefreshenabled (true);}}); }

Four, the commonly used some attribute introduction:

Pull-to-refresh can also define some attributes in XML:

Ptrrefreshableviewbackground sets the background color of the entire Mpullrefreshlistview

Ptrheaderbackground sets the background color of the dropdown header or pull footer

Ptrheadertextcolor is used to set the header and footer the color of the Chinese text

Ptrheadersubtextcolor used to set the color of the last refresh time in header and footer

Ptrshowindicator If True will appear in the Mpullrefreshlistview icon, upper right corner and lower right corner, very interesting.

Ptrheadertextappearance, Ptrsubheadertextappearance set the type color of the font in the pull header or pull footer, etc.

Ptrrotatedrawablewhilepulling whether the drop-down is rotated when the animation is set to rotate.

Summary: In fact, it is not difficult to achieve ListView refresh, we may often see such a component exists: Xlistview, this component should be beginners in Android, many people have seen, this is a lot of people to define their own written ListView Drop-down refresh, To realize the function is no problem, but the individual has always felt the effect of the experience is too poor. The Pulltorefresh Drop-down refresh is always used in the project.
Well, today's sharing is here, write the inadequacies of the place and do not understand where you can leave a message to discuss learning and exchange!
Share your own It Resource Library QQ Group: 459756676 is mainly to help IT industry beginners to share video learning materials, as long as you are it enthusiasts can enter the common learning!

The above is a small set of Android to introduce the use of Pulltorefresh complete ListView Drop-down Refresh and left-slip delete function, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.