Maxwin-z/xlistview-android (Pull-up reload) source code Analysis (ii)

Source: Internet
Author: User

Reprint please specify the source http://blog.csdn.net/crazy__chen/article/details/45980399

Source file http://download.csdn.net/detail/kangaroo835127729/8736887

This article is mainly posted Xlistview source code and a use instance, not too much to explain

Using instances, mainactivity

public class Mainactivity extends Activity {private linkedlist<string> listItems = null;    Private Xlistview ListView = null;     Private arrayadapter<string> adapter; Private string[] Mstrings = {"Aaaaaa", "bbbbbb", "CCCCCC", "dddddd", "eeeeee", "Ffffff", "GGGGGG"     , "Hhhhhh", "IIIIII", "JJJJJJ", "Kkkkkk", "llllll", "Mmmmmm", "nnnnnn",};    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                      Setcontentview (R.layout.activity_main);        ListView = (Xlistview) Findviewbyid (r.id.mlist); Listview.setxlistviewlistener (New Ixlistviewlistener () {@Overridepublic void Onrefresh () {new Getdatatask (true). Execute ();}               @Overridepublic void Onloadmore () {new Getdatatask (false). Execute ();}});        ListItems = new linkedlist<string> ();        Listitems.addall (Arrays.aslist (mstrings)); adapter = new Arrayadapter<string> (thisAndroid.        R.layout.simple_list_item_1, ListItems);        Listview.setadapter (adapter);    Listview.setpullloadenable (TRUE);         } private class Getdatatask extends Asynctask<void, Void, string[]> {private Boolean isdropdown;        Public Getdatatask (Boolean isdropdown) {this.isdropdown = Isdropdown; } @Override protected string[] Doinbackground (Void ... params) {try {Thread.slee            P (1000);            } catch (Interruptedexception e) {;        } return mstrings; } @Override protected void OnPostExecute (string[] result) {if (isdropdown) {Li                Stitems.addfirst ("Added after Drop");                                                    Adapter.notifydatasetchanged ();            Listview.stoprefresh ();                } else {Listitems.add ("Added after on Bottom");      Adapter.notifydatasetchanged ();          Listview.stoploadmore ();        } super.onpostexecute (Result); }    }}

Xlistview

public class Xlistview extends ListView implements Onscrolllistener {private float mlasty =-1;//Save Event y/** * for pull-down , sliding back to */private Scroller Mscroller; Used for scroll backprivate onscrolllistener mscrolllistener; User ' s scroll listener//the interface to trigger refresh and load More.private ixlistviewlistener mlistviewlistener;/* * Drop-down head */private xlistviewheader mheaderview;/** * drop-down head body, used to calculate the height of the head * when not refreshed, is hidden */private relativelayout mheaderviewcont ent;/** * drop-down arrow */private TextView mheadertimeview;/** * drop-down head height */private int mheaderviewheight;/** * can pull down refresh */private Boo Lean Menablepullrefresh = true;/** * is refreshing, false indicates that the */private Boolean mpullrefreshing = False is being refreshed; is refreashing.//--footer Viewprivate Xlistviewfooter Mfooterview;private boolean menablepullload;private boolean MP  Ullloading;private Boolean misfooterready = false;//Total list items, used to detect are at the bottom of listview.private int mtotalitemcount;//for Mscroller, scroll to header or Footer.private int mscrollback;/** * Head slide return */private final static int scrollback_header = 0;/** * Footer slide back to */private final static int scrollback_footer = 1;private final static int scroll_duration = 400; Scroll back durationprivate final static int pull_load_more_delta = 50; When pulling up >= 50px//at bottom, trigger//load more.private final static float Offset_radio = 1.8f; Support for IOS like pull//feature./** * @param context */public Xlistview (context context) {super (context); Initwithcontex T (context);} Public Xlistview (context context, AttributeSet Attrs) {Super (context, attrs); Initwithcontext (context);} Public Xlistview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); Initwithcontext ( context);} private void Initwithcontext (context context) {Mscroller = new Scroller (context, new Decelerateinterpolator ());// Xlistview need the scroll event, and it'll dispatch the event to//user ' s listener (as a proxy). Super.setonscrolllistene R (this);//initializationDrop-down head Mheaderview = new Xlistviewheader (context); mheaderviewcontent = (relativelayout) Mheaderview.findviewbyid ( r.id.xlistview_header_content); Mheadertimeview = (TextView) Mheaderview.findviewbyid (r.id.xlistview_header_time); Addheaderview (Mheaderview);//Initialize Bottom Mfooterview = new Xlistviewfooter (context);// Initialize the drop head height mheaderview.getviewtreeobserver (). Addongloballayoutlistener (New Ongloballayoutlistener () {@ overridepublic void Ongloballayout () {mheaderviewheight = Mheaderviewcontent.getheight ();// Get the height of the drop Head getviewtreeobserver (). Removeglobalonlayoutlistener (this);});}  @Overridepublic void Setadapter (ListAdapter adapter) {/* * will pull up loads more footer join the bottom of the ListView * and ensure that only one */if is added (Misfooterready = = False) {Misfooterready = True;addfooterview (Mfooterview);//listview Native method}super.setadapter (adapter);} /** * Set the pull-down refresh function to open * @param enable */public void Setpullrefreshenable (Boolean enable) {Menablepullrefresh = Enable;if (!m Enablepullrefresh) {//Do not open, hide Head mheaderviewcontent.setvisibility (view.invisible);} else {MheaderviEwcontent.setvisibility (view.visible);}} /** * Set the pull-up load more features open * If you want to turn on, you must actively call this function * @param enable */public void Setpullloadenable (Boolean enable) {Menablepullload = Enable;if (!menablepullload) {//if mfooterview.hide () is not turned on;//Hide Footermfooterview.setonclicklistener (null);//Cancel monitoring// Make sure "pulled up" don't show a line in bottom when the ListView with one page//ensures that the split lines between the ListView item disappear (last) setfooterdivide Rsenabled (false);//listview Native Method} else {mpullloading = False;mfooterview.show (); Mfooterview.setstate ( Xlistviewfooter.state_normal);//make sure "Pull up" don ' t show a line in bottom when the ListView with one page Setfooterdivi Dersenabled (TRUE);//Both "pull Up" and "click" To invoke Load More.mFooterView.setOnClickListener (new Onclicklistener () {@Overridepublic void OnClick (View v) {startloadmore ();}});}} /** * Stop Refresh, reset header view. * Stop Refresh, reset head */public void Stoprefresh () {if (mpullrefreshing = = true) {mpullrefreshing = False;resetheaderheight ();}} /** * Stop load more, reset footer view.* Stop loading more, reset footer */public void Stoploadmore () {if (mpullloading = = true) {mpullloading = False;mfooterview.setstate (xlis Tviewfooter.state_normal);}} /** * Set Last Refresh time * Sets final down refresh times * @param */public void Setrefreshtime (String time) {Mheadertimeview.settex T (time);} private void invokeonscrolling () {if (Mscrolllistener instanceof Onxscrolllistener) {Onxscrolllistener L = ( Onxscrolllistener) mscrolllistener;l.onxscrolling (this);}} /** * Update Head Height * This function is used to pull down when recording how much is pulled down * @param delta */private void Updateheaderheight (float delta) {Mheaderview.setvisiablehei ght (int) delta+ mheaderview.getvisiableheight ()); if (Menablepullrefresh &&!mpullrefreshing) {//Not in refresh State, Update arrows if (Mheaderview.getvisiableheight () > Mheaderviewheight) {mheaderview.setstate (Xlistviewheader.state_ready) ;} else {mheaderview.setstate (xlistviewheader.state_normal);}} Slide to head setselection (0); Scroll to top each time}/** * Reset header view ' s height. * Reset Head height */private void resetheaderheight () {int height =Mheaderview.getvisiableheight (); if (height = = 0)//not visible.return;//refreshing and header isn ' t shown fully. Do nothing.//is refreshing, or the head is not fully displayed, return if (mpullrefreshing && height <= mheaderviewheight) {return;} int finalheight = 0; The default final height, which means to let the head disappear//is refreshing, just scroll back to show all the header.//are refreshing, and the drop-down header fully displays if (Mpullrefreshing &AMP;&A mp Height > mheaderviewheight) {finalheight = Mheaderviewheight;} Mscrollback = scrollback_header;//from the current position, returning to the head is hidden mscroller.startscroll (0, height, 0, Finalheight-height,scroll_ DURATION);//Trigger Computescrollinvalidate ();} /** * Update footer distance from bottom * @param delta */private void Updatefooterheight (float delta) {int height = Mfooterview.getbottommarg  In () + (int) delta;if (menablepullload &&!mpullloading) {if (height > Pull_load_more_delta) {//height enough To invoke load pull up enough well paid to load//More.mFooterView.setState (Xlistviewfooter.state_ready);} else {mfooterview.setstate (xlistviewfooter.state_normal);}} Mfooterview.setbottommaRgin (height);//setselection (mTotalItemCount-1); Scroll to bottom}/** * Reset footer position */private void Resetfooterheight () {int bottommargin = Mfooterview.getbottommargin (); if (BottomMargin > 0) {mscrollback = Scrollback_footer;mscroller.startscroll (0, bottommargin, 0,-bottommargin, Scroll_duration); invalidate ();}} private void Startloadmore () {mpullloading = True;mfooterview.setstate (xlistviewfooter.state_loading); Mlistviewlistener! = null) {Mlistviewlistener.onloadmore ();}} @Overridepublic boolean ontouchevent (motionevent ev) {if (mlasty = =-1) {//Get touch y-coordinate mlasty = Ev.getrawy ();} Switch (ev.getaction ()) {Case MotionEvent.ACTION_DOWN:mLastY = Ev.getrawy (); Break;case MotionEvent.ACTION_MOVE:final float DeltaY = Ev.getrawy ()-mlasty;//pull down or pull up how much offsetmlasty = Ev.getrawy (); if (getfirstvisibleposition () = = 0&& (Mheaderview.getvisiableheight () > 0 | | deltay > 0)) {//The first item is visible and the header is partially displayed or pulled down, it is in the drop-down refresh state//The primary item is showing, and the header has a shown or pull Down.updateheaderhEight (Deltay/offset_radio); invokeonscrolling ();} else if (getlastvisibleposition () = = mtotalitemcount-1&& (mfooterview.getbottommargin () > 0 | | DeltaY < 0) {//The last item is visible and footer is either pulled up or pulled up, it indicates a pull-up refresh state/previous item, already pulled up or want to pull up.updatefooterheight (-delt Ay/offset_radio);} Break;default://action_upmlasty =-1; Resetif (getfirstvisibleposition () = = 0) {//Invoke Refreshif (menablepullrefresh&& Mheaderview.getvisiableheight () > mheaderviewheight) {mpullrefreshing = True;mheaderview.setstate ( xlistviewheader.state_refreshing); if (mlistviewlistener! = null) {Mlistviewlistener.onrefresh ();}} Resetheaderheight ();} else if (getlastvisibleposition () = = mTotalItemCount-1) {//Invoke load More.if (menablepullload && Mfootervi Ew.getbottommargin () > Pull_load_more_delta &&!mpullloading) {Startloadmore ();} Resetfooterheight ();} break;} return super.ontouchevent (EV);} @Overridepublic void Computescroll () {if (Mscroller.compuTescrolloffset ()) {if (Mscrollback = = Scrollback_header) {mheaderview.setvisiableheight (Mscroller.getcurry ());} else {Mfooterview.setbottommargin (Mscroller.getcurry ());} Postinvalidate (); invokeonscrolling ();} Super.computescroll ();} @Overridepublic void Setonscrolllistener (Onscrolllistener l) {mscrolllistener = l;} @Overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {if (Mscrolllistener! = null) { Mscrolllistener.onscrollstatechanged (view, scrollstate);}} @Overridepublic void Onscroll (abslistview view, int firstvisibleitem,int visibleitemcount, int totalitemcount) {//Send T o user ' s listenermtotalitemcount = totalitemcount;if (Mscrolllistener! = null) {Mscrolllistener.onscroll (view, Firstvisibleitem, Visibleitemcount,totalitemcount);}} public void Setxlistviewlistener (Ixlistviewlistener l) {mlistviewlistener = l;} /** * Can listen listview.onscrolllistener or this one. It would invoke * onxscrolling when header/footer scroll back. */public Interface OnxscrolllisteneR extends Onscrolllistener {public void onxscrolling (view view); /** * Implements this interface to get Refresh/load more event. * Dropdown and pull-up listener */public interface Ixlistviewlistener {public void Onrefresh ();p ublic void Onloadmore ();}}

Xlistviewheader

public class Xlistviewheader extends LinearLayout {/** * drop-down layout body */private linearlayout mcontainer;/** * drop-down arrow */private Ima  Geview marrowimageview;/** * Ring progress bar */private ProgressBar mprogressbar;/** * hint text */private TextView mhinttextview;private int mstate = state_normal;private Animation mrotateupanim;private Animation mrotatedownanim;/** * Animation time */private final in T rotate_anim_duration = 180;public final static int state_normal = 0;//normal state public final static int state_ready = 1;//Pull Ready Refresh public final static int state_refreshing = 2;//Loading public xlistviewheader (context context) {super (context); Initview ( context);} /** * @param context * @param attrs */public Xlistviewheader (context context, AttributeSet Attrs) {Super (context, attrs); I Nitview (context);} private void Initview (context context) {///initial case, set dropdown refresh view height to 0linearlayout.layoutparams LP = new Linearlayout.layoutparams (layoutparams.fill_parent, 0); Mcontainer = (linearlayout) layoutinflater.from (context). Inflate (R.layout.xlistview_header, null); AddView (Mcontainer, LP); setgravity (gravity.bottom); Marrowimageview = (ImageView) Findviewbyid (r.id.xlistview_ Header_arrow); Mhinttextview = (TextView) Findviewbyid (r.id.xlistview_header_hint_textview); Mprogressbar = ( ProgressBar) Findviewbyid (R.id.xlistview_header_progressbar);//Rotate animation Mrotateupanim = new Rotateanimation (0.0f,- 180.0f,animation.relative_to_self, 0.5f, animation.relative_to_self,0.5f);//Set animation time Mrotateupanim.setduration ( rotate_anim_duration);//The animation stops at the last frame, that is, the state after the animation is preserved mrotateupanim.setfillafter (true);//Rotate animation Mrotatedownanim = new Rotateanimation ( -180.0f, 0.0f,animation.relative_to_self, 0.5f, animation.relative_to_self,0.5f); Mrotatedownanim.setduration (rotate_anim_duration); Mrotatedownanim.setfillafter (true);} public void SetState (int.) {if (state = = mstate) return; if (state = = state_refreshing) {//Show Progress Marrowimageview.clear Animation (); marrowimageview.setvisibility (view.invisible); mprogressbar.setvisibility (view.visible);} else {//show arrows picture marrowimageview.setvisibility (View.visible); mprogressbar.setvisibility (view.invisible);} Switch (state) {case State_normal:if (mstate = = State_ready) {marrowimageview.startanimation (Mrotatedownanim);} if (mstate = = state_refreshing) {marrowimageview.clearanimation ();} Mhinttextview.settext (r.string.xlistview_header_hint_normal); Break;case state_ready:if (mState! = STATE_READY) { Marrowimageview.clearanimation (); marrowimageview.startanimation (Mrotateupanim); Mhinttextview.settext ( R.string.xlistview_header_hint_ready);} Break;case STATE_REFRESHING:mHintTextView.setText (r.string.xlistview_header_hint_loading); break;default:}mstate = State;} /** * Set the drop head effective height * @param height */public void setvisiableheight (int height) {if (height < 0) height = 0; Linearlayout.layoutparams LP = (linearlayout.layoutparams) mcontainer.getlayoutparams (); lp.height = height; MCONTAINER.SETLAYOUTPARAMS (LP);} /** * Get the drop head effective height * @return */public int getvisiableheight () {return mcontainer.getlayoutparams (). Height;}}

Xlistviewfooter
public class Xlistviewfooter extends LinearLayout {public final static int state_normal = 0;//normal state public final static int State_ready = 1;//Pull ready to refresh public final static int state_loading = 2;//loading private Context mcontext;private View Mcontentview ;p rivate View mprogressbar;private TextView mhintview;public xlistviewfooter (context context) {super (context); Initview (context);} Public Xlistviewfooter (context context, AttributeSet Attrs) {Super (context, attrs); Initview (context);} /** * Set Status * @param state */public void setState (int state) {mhintview.setvisibility (view.invisible); Mprogressbar.setvisibility (view.invisible); mhintview.setvisibility (view.invisible); if (state = = STATE_READY) { Mhintview.setvisibility (view.visible); Mhintview.settext (R.string.xlistview_footer_hint_ready);} else if (state = = state_loading) {mprogressbar.setvisibility (view.visible);} else {mhintview.setvisibility ( view.visible); Mhintview.settext (R.string.xlistview_footer_hint_normal);}} /** * Set the height of the bottom of the footer * @param height */public void setbottommargin (int height) {if (height < 0) return; Linearlayout.layoutparams LP = (linearlayout.layoutparams) mcontentview.getlayoutparams (); lp.bottomMargin = height; MCONTENTVIEW.SETLAYOUTPARAMS (LP);} /** * Get the height of the bottom of the footer * @return */public int getbottommargin () {linearlayout.layoutparams LP = (linearlayout.layoutparams) Mcontentview.getlayoutparams (); return lp.bottommargin;} /** * Normal status */public void Normal () {mhintview.setvisibility (view.visible); Mprogressbar.setvisibility ( View.gone);} /** * Loading status */public void loading () {mhintview.setvisibility (view.gone); Mprogressbar.setvisibility ( view.visible);} /** * Hide Footer when disable pulling load more */public void Hide () {linearlayout.layoutparams LP = (Linearlayout.layoutpar AMS) Mcontentview.getlayoutparams (); lp.height = 0;MCONTENTVIEW.SETLAYOUTPARAMS (LP);} /** * Show footer */public void Show () {linearlayout.layoutparams LP = (linearlayout.layoutparams) Mcontentview.getlayoutparams (); lp.height = Layoutparams.wraP_CONTENT;MCONTENTVIEW.SETLAYOUTPARAMS (LP);} /** * Initialize layout * @param context */private void Initview (context context) {Mcontext = context; LinearLayout Moreview = (linearlayout) layoutinflater.from (Mcontext). Inflate (r.layout.xlistview_footer, NULL); AddView (Moreview); Moreview.setlayoutparams (New Linearlayout.layoutparams (Layoutparams.fill_parent, layoutparams.wrap_content)); Mcontentview = Moreview.findviewbyid (r.id.xlistview_footer_content); MProgressBar = Moreview.findviewbyid (r.id.xlistview_footer_progressbar); Mhintview = (TextView) Moreview.findviewbyid ( R.id.xlistview_footer_hint_textview);}}

Maxwin-z/xlistview-android (Pull-up reload) source code Analysis (ii)

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.