Android Custom Control development actual implementation ListView Drop-down Refresh Instance Code _android

Source: Internet
Author: User

This blog introduces a common Android feature--listview Drop-down refresh:

First pull down when the phone shows such an interface:


The following code is a custom stick-like control:

<span style= "Font-family:comic sans ms,sans-serif; font-size:16px; "
>package Com.dhsr.smartID.view;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import android.view.Gravity;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import android.view.animation.Animation;
Import android.view.animation.RotateAnimation;
Import Android.widget.ImageView;
Import Android.widget.LinearLayout;
Import Android.widget.ProgressBar;
Import Android.widget.TextView;
Import COM.EXAMPLE.SIRELINKSCANAPP.R; /** * Custom control, complete the drop time ListView Display "icon and prompt is refreshing ..." layout * * @author CYF */public class Xlistviewheader extends LinearLayout {PR
Ivate LinearLayout Mcontainer;
Picture Private ImageView Marrowimageview;
Circular progress bar private ProgressBar Mprogressbar;
Private TextView Mhinttextview;
State private int mstate = State_normal;
Animation private Animation Mrotateupanim;
Private Animation Mrotatedownanim;
Private final int rotate_anim_duration = 180; Normal public final static int State_normal= 0;
Ready to refresh public final static int state_ready = 1;
Public final static int state_refreshing = 2 in refresh; Public Xlistviewheader {Super (context), Initview (context),/** * @param context * @param attrs * * Publ IC Xlistviewheader (context, AttributeSet attrs) {Super (context, attrs), Initview (context),/** * "Release can refresh ... Refreshing ... "layout * * @param context */private void Initview (contexts context) {//initial situation, set Drop-down refresh view height of 0 Linearlayout.layoutparam
S LP = new Linearlayout.layoutparams (layoutparams.match_parent, 0);
Mcontainer = (linearlayout) layoutinflater.from (context). Inflate (R.layout.xlistview_header, NULL);
Load View AddView (Mcontainer, LP);
Center mode setgravity (Gravity.bottom);
Initializes the control 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); Set Animation Mrotateupanim = new Rotateanimation (0.0f,-180.0f, Animation.relative_to_self, 0.5f, Animation.relative_to_self, 0.5f);
Mrotateupanim.setduration (rotate_anim_duration);
Mrotateupanim.setfillafter (TRUE);
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); /** * performs the corresponding function according to the dropdown state, starts and stops the corresponding animation * * * @param states/public void SetState (int state) {if (= = mstate) return; if (
state = = state_refreshing) {//Show Progress marrowimageview.clearanimation (); marrowimageview.setvisibility (View.INVISIBLE);
Mprogressbar.setvisibility (view.visible); else {//Show arrow picture marrowimageview.setvisibility (view.visible); mprogressbar.setvisibility (view.invisible);} switch (
State) {case State_normal:if (mstate = = State_ready) {//Start animation marrowimageview.startanimation (Mrotatedownanim);}//Refresh if (mstate = = state_refreshing) {//Clear animation 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;
public void setvisiableheight (int height) {if (height < 0) height = 0;
Linearlayout.layoutparams LP = (linearlayout.layoutparams) mcontainer. Getlayoutparams ();
Lp.height = height;
MCONTAINER.SETLAYOUTPARAMS (LP);
public int getvisiableheight () {return mcontainer.getheight ();}}  </span>

The next step is to customize your own ListView inheritance to the Android ListView and add new methods to yourself.

<span style= "Font-family:comic sans ms,sans-serif; font-size:16px; "
>package Com.dhsr.smartID.view;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import android.view.MotionEvent;
Import Android.view.View;
Import Android.view.ViewTreeObserver.OnGlobalLayoutListener;
Import Android.view.animation.DecelerateInterpolator;
Import Android.widget.AbsListView;
Import Android.widget.AbsListView.OnScrollListener;
Import Android.widget.ListAdapter;
Import Android.widget.ListView;
Import Android.widget.RelativeLayout;
Import Android.widget.Scroller;
Import Android.widget.TextView;
Import COM.EXAMPLE.SIRELINKSCANAPP.R; /** * Custom ListView * * * @author CYF * */public class Xlistview extends ListView implements Onscrolllistener {private fin
Al String TAG = "Xlistview";
Private float mlasty =-1;
Private Scroller Mscroller;
Sliding private Onscrolllistener Mscrolllistener;
Create a monitor for the outside world private Ixlistviewlistener mlistviewlistener; The custom control that you just defined is private xlistviewheader Mheaderview
Private Relativelayout mheaderviewcontent;
Private TextView Mheadertimeview; private int mheaderviewheight;
Header view ' s height private Boolean menablepullrefresh = true; Private Boolean mpullrefreshing = false;
Is refreashing.
Private Boolean menablepullload;
Private Boolean mpullloading;
Private Boolean misfooterready = false;
Total list items, used to detect are at the bottom of ListView.
private int mtotalitemcount;
For Mscroller, scroll back from header or footer.
private int mscrollback;
Private final static int scrollback_header = 0;
Private final static int scrollback_footer = 1; Private final static int scroll_duration = 400; Scroll back duration private final static int pull_load_more_delta = 50;
When pull up >= 50px//At bottom, trigger//load more. Private final static float Offset_radio = 1.8f;
Support IOS like pull//feature. /** * @param context/public Xlistview {Super (context), initwithcontext (context), public XlistvIew (context, AttributeSet attrs) {Super (context, attrs); Initwithcontext (context);} public Xlistview (context Co ntext, attributeset attrs, int defstyle) {Super (context, attrs, Defstyle); Initwithcontext (context);}/** * Initialization control * * param context/private void Initwithcontext {Mscroller = new Scroller (context, new Decelerateinterpola
Tor ());
Super.setonscrolllistener (this);
Mheaderview = new Xlistviewheader (context);
Mheaderviewcontent = (relativelayout) mheaderview. Findviewbyid (r.id.xlistview_header_content);
Mheadertimeview = (TextView) mheaderview. Findviewbyid (R.id.xlistview_header_time);
Addheaderview (Mheaderview, NULL, FALSE); Mheaderview.getviewtreeobserver (). Addongloballayoutlistener (New Ongloballayoutlistener () {@Override public void Ongloballayout () {mheaderviewheight = Mheaderviewcontent.getheight (); Getviewtreeobserver ().
Removeglobalonlayoutlistener (this);
}
}); @Override public void Setadapter (ListAdapter adapter) {//Make sure XlistvieWfooter is the last footer view, with only add once. if (Misfooterready = = False) {if (menablepullload) {Misfooterready = true;//Addfooterview (Mfooterview);}} Super.seta
Dapter (adapter); public void Setpullrefreshenable (Boolean enable) {Menablepullrefresh = enable; if (!menablepullrefresh) {//disable, H
IDE the Content mheaderviewcontent.setvisibility (view.invisible);
else {mheaderviewcontent.setvisibility (view.visible);}} 
/** * Stop refreshing */public void Stoprefresh () {if (mpullrefreshing = = true) {mpullrefreshing = false; Resetheaderheight ();}} To perform a drop-down refresh when entering an activity (Startrefresh) {if (mpullrefreshing = = False) {mpullrefreshing = true; Mheaderview.
SetState (xlistviewheader.state_refreshing);
Mheaderview.setvisiableheight (90);
if (Mlistviewlistener!= null) {Mlistviewlistener.onrefresh ();}}
/** * Stop load more, reset footer view. /public void Stoploadmore () {if (mpullloading = = true) {mpullloading = false;}/** * Set last Refresh time * * @pa RamTime/public void Setrefreshtime (String time) {Mheadertimeview.settext (time);} private void Invokeonscrolling () {if (
Mscrolllistener instanceof Onxscrolllistener) {Onxscrolllistener L = (onxscrolllistener) MScrollListener;
L.onxscrolling (this); }} private void Updateheaderheight (float delta) {mheaderview.setvisiableheight (int) Delta +
Mheaderview.getvisiableheight ()); if (Menablepullrefresh &&!mpullrefreshing) {//Not in refresh state, update arrow if (Mheaderview.getvisiableheight () > Mheaderviewheight) {mheaderview.setstate (xlistviewheader.state_ready);} else {mheaderview.setstate (
Xlistviewheader.state_normal); } if (mpullloading) {//disable, hide the content mheaderviewcontent.setvisibility (view.invisible);} else {MHEADERVIEWC
Ontent.setvisibility (view.visible); } setselection (0);
Scroll to top each time}/** * Reset header view ' s height. * * private void Resetheaderheight () {int height = mheaderview.getvisiableheight (); if (height = 0)//not visible. retur
N RefresHing and header isn ' t shown fully.
Doing nothing. if (mpullrefreshing && height <= mheaderviewheight) {return;} int finalheight = 0;
Default:scroll back to dismiss header.
is refreshing, just scroll, and the all header. if (mpullrefreshing && height > mheaderviewheight) {finalheight = mheaderviewheight;} mscrollback = Scrollbac
K_header;
Mscroller.startscroll (0, height, 0, finalheight-height, scroll_duration);
Trigger Computescroll invalidate (); /** * Touch screen Monitor/@Override public boolean ontouchevent (motionevent ev) {if (mlasty = = 1) {mlasty = Ev.getrawy ();} SWITC  H (ev.getaction ()) {Case MotionEvent.ACTION_DOWN:mLastY = Ev.getrawy (), break, case MotionEvent.ACTION_MOVE:final float
DeltaY = Ev.getrawy ()-mlasty;
DLOG.I (TAG, "DeltaY is" + DeltaY);
Mlasty = Ev.getrawy (); if (getfirstvisibleposition () = 0 && (mheaderview.getvisiableheight () > 0 | | deltay > 0)) {//the The
The EM is showing, the header has shown or pull down. UPdateheaderheight (Deltay/offset_radio);
Invokeonscrolling (); 
else if (getlastvisibleposition () = = mTotalItemCount-1) {//last item, already pulled up or want to pull up.} Default:mlasty =-1; Reset if (getfirstvisibleposition () = = 0) {//Invoke refresh if (!mpullrefreshing && Menablepullrefresh &&
amp;!mpullloading && mheaderview.getvisiableheight () > mheaderviewheight) {mpullrefreshing = true;
Mheaderview.setstate (xlistviewheader.state_refreshing);
DLOG.I (TAG, "invoke Refresh");
if (Mlistviewlistener!= null) {//The new method is executed at this time Mlistviewlistener.onrefresh ();}
Resetheaderheight (); else if (getlastvisibleposition () = = mTotalItemCount-1) {//Invoke load more. if (!mpullloading && Menablepul
Lload &&!mpullrefreshing) {//DLOG.I (TAG, invoke load more);}
Break
return super.ontouchevent (EV); @Override public void Computescroll () {if (Mscroller.computescrolloffset ()) {if (Mscrollback = = Scrollback_header) {m HeadErview.setvisiableheight (Mscroller.getcurry ());
} else {} postinvalidate ();
Invokeonscrolling ();
} super.computescroll (); @Override public void Setonscrolllistener (Onscrolllistener l) {mscrolllistener = l;}/** * Callback when scrolling, callback 2-3 times, the finger is not thrown off the callback 2 times, SC Rollstate = 2 This time does not recall the 1th time: scrollstate = * Scroll_state_touch_scroll (1) is scrolling 2nd times: scrollstate = * scroll_state_fling (2) fingers did throw Action (Slide the finger away from the screen) for the 3rd time: scrollstate = * Scroll_state_idle (0) stop rolling/@Override public void onscrollstatechanged ( Abslistview view, int scrollstate) {if (Mscrolllistener!= null) {mscrolllistener.onscrollstatechanged (view, ScrollStat
e); ///slide to the bottom, automatically load more. You can also disable this logical if (getlastvisibleposition () = = MTotalItemCount-1 && scrollstate = = Scroll_state_idle) {if (!mpullload
ing && menablepullload &&!mpullrefreshing) {//DLOG.I (TAG, invoke load more);} /** * The callback when scrolling, stop the callback when scrolling, callback once when clicked/@Override public void onscroll (Abslistview view, int firstvisibleitem, int visible
ItemCount, int totalitemcount) {Send to user ' s listener mtotalitemcount = Totalitemcount;
if (Mscrolllistener!= null) {Mscrolllistener.onscroll (view, Firstvisibleitem, VisibleItemCount, Totalitemcount);}  
public void Setxlistviewlistener (Ixlistviewlistener l) {mlistviewlistener = l;}/** * Monitoring ListView sliding Events * * @author CYF * * * Public Interface Onxscrolllistener extends Onscrolllistener {public void onxscrolling (view view);}/** * Custom interface/P 
Ublic interface Ixlistviewlistener {//Drop-down Refresh method public void Onrefresh ();//The method to execute on pull load is public void Onloadmore ();}}  </span>

ListView in the mainactivity XML file do not use Android ListView, with the Custom ListView (add package name)

<span style= "Font-family:comic sans ms,sans-serif; font-size:16px; "
>package Com.test.andy;
Import java.util.ArrayList;
Import Com.test.andy.view.XListView;
Import Com.test.andy.view.XListView.IXListViewListener;
Import COM.TEST.ANDY.R;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.widget.ArrayAdapter; /** * xlistviewactivity * Implementation of Ixlistviewlistener interface is to achieve the drop down Refresh method * @author CYF * */public class Xlistviewactivity extends Activity implements Ixlistviewlistener {//Custom ListView private Xlistview Mlistview; private arrayadapter<string>
Madapter;
Private arraylist<string> items = new arraylist<string> ();
Private Handler Mhandler;
private int start = 0;
private int refreshcnt = 0; /** called the activity is a. * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.main);
Loading 20 data Geneitems () when initializing; Mlistview = (Xlistview) FindvieWbyid (R.id.xlistview);
Mlistview.setpullloadenable (TRUE);
Madapter = new Arrayadapter<string> (this, r.layout.list_item, items);
Mlistview.setadapter (Madapter);
Mlistview.setpullrefreshenable (FALSE);
Mlistview.setxlistviewlistener (this);
Mhandler = new Handler ();
Mlistview.startrefresh ();
private void Geneitems () {for (int i = 0; I!= ++i) {items.add ("Refresh cnt" + (++start));}
private void OnLoad () {Mlistview.stoprefresh (); Mlistview.stoploadmore (); Mlistview.setrefreshtime ("just"); @Override public void Onrefresh () {mhandler.postdelayed, new Runnable () {@Override public void run () {start = ++refreshcnt; items.
Clear ();
Geneitems ();
Madapter.notifydatasetchanged ();
Madapter = new Arrayadapter<string> (Xlistviewactivity.this, R.layout.list_item, items);
Mlistview.setadapter (Madapter);
OnLoad ();
}, 2000); @Override public void Onloadmore () {mhandler.postdelayed (new Runnable () {@Override public void run () {geneitems (); MA Dapter.notifydatasetchanged ();
OnLoad ();
}, 2000);  }} </span>

Important code is summed up here, I hope to bring you help, thank you.

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.