Drop-down Refresh (ii)

Source: Internet
Author: User
Tags gety

First look at the main layout activity_main.xml

<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 "    android:background= "@color/white"    tools:context= ". Mainactivity ">    <com.imooc.listviewfrashdemo1.reflashlistview        android:id=" @+id/listview "        Android:layout_width= "Fill_parent"        android:layout_height= "fill_parent"        android:background= "@color/ White "        android:cachecolorhint=" #00000000 "        android:dividerheight=" 5dip "/></relativelayout>

Re-header_layout.xml layout

<?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=" wrap_content "android:orientation=" vertical " > <relativelayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" a Ndroid:paddingbottom= "10dip" android:paddingtop= "10dip" > <linearlayout android:id= "@+id/la Yout "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:la Yout_centerinparent= "true" android:gravity= "center" android:orientation= "vertical" > & Lt TextView android:id= "@+id/tip" android:layout_width= "Wrap_content" Android:la yout_height= "Wrap_content" android:text= "drop-down can be refreshed!           "/> <textview android:id=" @+id/lastupdate_time "     Android:layout_width= "Wrap_content" android:layout_height= "wrap_content"/> </linearlayou t> <imageview android:id= "@+id/arrow" android:layout_width= "Wrap_content" an droid:layout_height= "Wrap_content" android:layout_toleftof= "@id/layout" android:layout_marginright= " 20dip "android:src=" @drawable/pull_to_refresh_arrow "/> <progressbar android:id=" @+id/p            Rogress "style="? Android:attr/progressbarstylesmall "Android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:layout_toleftof= "@id/layout" android:layout_marginright = "20dip" android:visibility= "Gone"/> </RelativeLayout></LinearLayout>

Look at the layout of each item in the ListView


<?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:orientation=" vertical " > <linearlayout android:layout_width= "fill_parent" android:layout_height= "60dip" Android:gra        Vity= "center_vertical" android:background= "@drawable/app_item_bg" android:orientation= "Horizontal" > <imageview android:id= "@+id/item3_apkiv" android:layout_width= "50dip" android:layou        t_height= "50dip" android:background= "@drawable/test_icon" android:layout_marginleft= "10dip"/>            <linearlayout android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_weight= "1" android:layout_marginleft= "10dip" android:orientation= "vertical"            ;          <textview      Android:id= "@+id/item3_apkname" android:layout_width= "Wrap_content" Android:layout_hei ght= "Wrap_content" android:text= "Application Name" android:textcolor= "@color/black" and Roid:textsize= "18dip"/> <textview android:id= "@+id/item3_apkinfo" Android: Layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_margintop= "5        Dip "android:text=" Application Information "android:textsize=" 14dip "/> </LinearLayout> <button android:layout_width= "60dip" android:layout_height= "30dip" Android:backgroun            d= "@drawable/ic_launcher" android:id= "@+id/item3_dlbtn" android:layout_marginright= "10dip"        android:text= "Install"/> </LinearLayout> <textview android:id= "@+id/item3_apkdes" Android:layout_width= "FIll_parent "android:layout_height=" 30dip "android:layout_marginleft=" 5dip "android:layout_marginright = "5dip" android:gravity= "center_vertical" android:text= "Application description" android:textsize= "14dip"/></li Nearlayout>

The above three layouts can be seen, know a ballpark, this is not the main

Next look at the Bean class


Package Com.imooc.listviewfrashdemo1;public class Apkentity {private string Name;private string Des;private string info; Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getdes () {return des;} public void Setdes (String des) {this.des = des;} Public String GetInfo () {return info;} public void SetInfo (String info) {this.info = info;}}

Next look at the main process code


Package Com.imooc.listviewfrashdemo1;import Java.util.arraylist;import Android.app.activity;import Android.os.bundle;import Android.os.handler;import Com.example.listviewfrashdemo1.r;import Com.imooc.listviewfrashdemo1.reflashlistview.ireflashlistener;public class Mainactivity extends Activity implements Ireflashlistener {arraylist<apkentity> apk_list; Myadapter adapter; Reflashlistview listview, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( savedinstancestate);//Load layout--only one listviewsetcontentview (r.layout.activity_main);//Set Data SetData ();//Fill Data showlist ( apk_list);} /** * Set data source */private void SetData () {apk_list = new arraylist<apkentity> (); for (int i = 0; i < i++) {Apkenti Ty entity = new apkentity (), Entity.setname ("Default data"), Entity.setinfo ("50w user") Entity.setdes ("This is a magical application"); Apk_list.add (entity);}} private void Showlist (arraylist<apkentity> apk_list) {if (adapter = = NULL) {ListView = (Reflashlistview) Findviewby Id (R.id.listview);//Set the listener for this class, and thenImplements Ireflashlistenerlistview.setinterface (This): adapter = new Myadapter (this, apk_list);//If the adapter is null, Set the adapter to Listview.setadapter (adapter);} else {//If the adapter is not NULL, update the data source for notifydatasetchanged () Adapter.ondatechange (apk_list);}} /** * Callback method to implement refresh operation */@Overridepublic void Onreflush () {Handler Handler = new Handler (); handler.postdelayed (new Runnable () {@Overridepublic void Run () {//Gets the latest data setreflashdata ();//Notification interface displays showlist (apk_list);//Notify ListView to Refresh Data!!!!!!!!!!!!!! Listview.reflashcomplete ();}}, 2000);} private void Setreflashdata () {for (int i = 0; i < 2; i++) {apkentity entity = new apkentity (); Entity.setname ("Refresh Data"); E Ntity.setdes ("This is a magical application"); Entity.setinfo ("50w user"); Apk_list.add (0, entity);}}

Next look at the adapter code


Package Com.imooc.listviewfrashdemo1;import Java.util.arraylist;import Com.example.listviewfrashdemo1.r;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.ViewGroup ; Import Android.widget.baseadapter;import Android.widget.textview;public class Myadapter extends Baseadapter { Arraylist<apkentity> apk_list; Layoutinflater Inflater;public Myadapter (context context, arraylist<apkentity> apk_list) {this.apk_list = Apk_ List;this.inflater = Layoutinflater.from (context);} public void Ondatechange (arraylist<apkentity> apk_list) {this.apk_list = Apk_list;this.notifydatasetchanged ();} @Overridepublic int GetCount () {return apk_list.size ();} @Overridepublic Object getItem (int position) {return apk_list.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {apkentity entity = apk_list.get (position) ; Viewholder Holder;if (converTView = = null) {holder = new Viewholder (); Convertview = Inflater.inflate (r.layout.item_layout, null); HOLDER.NAME_TV = (Te Xtview) Convertview.findviewbyid (r.id.item3_apkname); holder.des_tv = (TextView) Convertview.findviewbyid ( R.id.item3_apkdes); Holder.info_tv = (TextView) Convertview.findviewbyid (r.id.item3_apkinfo); Convertview.settag ( Holder);} Else{holder = (Viewholder) Convertview.gettag ();} Holder.name_tv.setText (Entity.getname ()); Holder.des_tv.setText (Entity.getdes ()); Holder.info_tv.setText ( Entity.getinfo ()); return Convertview;} Class Viewholder {TextView name_tv; TextView Des_tv; TextView Info_tv;}}
Next look at the custom ListView class (inside the code details)


Package Com.imooc.listviewfrashdemo1;import Java.text.simpledateformat;import Java.util.date;import Android.content.context;import Android.util.attributeset;import Android.util.log;import Android.view.layoutinflater;import Android.view.motionevent;import Android.view.view;import Android.view.viewgroup;import Android.view.animation.rotateanimation;import Android.widget.abslistview;import Android.widget.abslistview.onscrolllistener;import Android.widget.imageview;import Android.widget.ListView; Import Android.widget.progressbar;import android.widget.textview;import com.example.listviewfrashdemo1.r;/** * Hide header Layout--first measure parent layout, layout height, set padding, then hide header layout, listview in Add header layout * Set Listener event * Determine ontouch time * Set listener load refreshed data */public class Reflashlistview extends ListView implements Onscrolllistener {View header;//top layout file; int headerheight;//height of top layout file; int firstvisibleitem;//the position of the currently first visible item, int scrollstate;//listview Current scrolling state; Boolean isremark;//tag, currently at the top of the listview; int starty;//the Y value when pressed, int state;//the current state; final int NONE = 0;//normal state; final int pull = 1;//hint drop-down state; final int relese = 2;//prompt release status; final int reflashing = 3;//refresh State; Ireflashlistener ireflushlistener;//refreshes the data interface/** * Three constructor methods, and initializes the view */public Reflashlistview (context context) {super (context); Initview ( context);} Public Reflashlistview (context context, AttributeSet Attrs) {Super (context, attrs); Initview (context);} Public Reflashlistview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); Initview ( context);} /** * Initialize interface, add top layout file to ListView */private void Initview (context context) {Layoutinflater inflater = Layoutinflater.from (co ntext); header = Inflater.inflate (r.layout.header_layout, NULL);//First measure parent layout, otherwise headerheight is 0measureView (header);// Gets the height of the header layout file Headerheight = Header.getmeasuredheight (); LOG.I ("tag", "headerheight =" + headerheight);//Hide Header Layout file toppadding (-headerheight);//listview Add header Layout This.addheaderview (header);//Set Slide monitor this.setonscrolllistener (this);} /** * Notifies the parent layout, occupies a wide, high, */private void Measureview (view view) {Viewgroup.layoutparAMS P = view.getlayoutparams (); if (p = = null) {p = new Viewgroup.layoutparams (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);} /** * Because the ListView does not limit height. How high the child is, the ListView gives it much space * But the ListView is limited in width, so it needs getchildmeasurespec */int width = viewgroup.getchildmeasurespec (0, 0 , p.width); int height;//Gets the height value of itme int tempheight = p.height;if (Tempheight > 0) {height = Measurespec.makemeasurespec ( tempheight,measurespec.exactly);} else {height = measurespec.makemeasurespec (0, measurespec.unspecified);} View.measure (width, height);} /** * Sets the top margin of the header layout;--look at the problem from the perspective of the parent layout */private void toppadding (int toppadding) {header.setpadding (header.getpaddingleft (), Toppadding,header.getpaddingright (), Header.getpaddingbottom ()); Header.invalidate ();} /** * Implement Interface method */@Overridepublic void onscroll (abslistview view, int firstvisibleitem,int visibleitemcount, int Totalitemco UNT) {this.firstvisibleitem = Firstvisibleitem;} @Overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {this.scrollstate = scrollstate;} /** * Implement Touch Method */@Overridepublic Boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {/** * If the finger is pressed, if Firstvisi Bleitem = = 0 Sets the mark to True, which represents the top pressed * and gets the coordinates of the y-axis distance */case MotionEvent.ACTION_DOWN:if (Firstvisibleitem = = 0) {Isremark = tr Ue;starty = (int) ev.gety ();} Break;case motionevent.action_move:/** * Judge the movement process operation; */onmove (EV); break;case MotionEvent.ACTION_UP:if (state = = Relese) { state = reflashing;//Load up-to-date data; Reflashviewbystate (); Ireflushlistener.onreflush ();} else if (state = = pull) {state = None;isremark = False;reflashviewbystate ();} break;} return super.ontouchevent (EV);} /** * When the finger is pressed */private void OnMove (motionevent ev) {//If it is not pressed at the top of the ListView, return directly, do not process if (!isremark) {return;} int tempy = (int) ev.gety ();//Gets the moving distance int space = tempy-starty;//Gets the padding value of the latest header layout int toppadding = Space-headerheight;s Witch (state) {/** * Determines the status value of the refresh arrow */case none://If you move it a little bit to the state--drop-down can refresh if (Space > 0) {///if it is normal, modify the state to a drop-down to refresh states = pull;// Change the interface display according to the current state; REFLASHVIEWBYstate ();} Break;case pull://Redraw The latest head layout hiding degree toppadding (toppadding);//If you change the state value directly if it is greater than 30 of the head layout height if (space-headerheight> 30& & scrollstate = = Scroll_state_touch_scroll) {//Modify status is--release can refresh state = Relese;reflashviewbystate ();} Break;case relese://Redraw The latest header layout hiding degree toppadding (toppadding); if (Space-headerheight < 30) {//Change state--the drop-down can be refreshed by the status = pull; Reflashviewbystate ();} else if (space <= 0) {//when space<=0, the visible item index is not 0state = none;//restore Isremark = False;reflashviewbystate ();} Break;}} /** * Changes the interface display according to the current state, */private void Reflashviewbystate () {TextView tip = (TextView) Header.findviewbyid (r.id.tip); I Mageview arrow = (ImageView) Header.findviewbyid (R.id.arrow); ProgressBar progress = (ProgressBar) Header.findviewbyid (r.id.progress); Rotateanimation anim = new Rotateanimation (0, 180,rotateanimation.relative_to_self, 0.5f,rotateanimation.relative_to _self, 0.5f); anim.setduration (+); Anim.setfillafter (true); Rotateanimation anim1 = new Rotateanimation (0,rotateanimation.relative_to_self, 0.5f,rotateanimation. Relative_to_self, 0.5f); anim1.setduration (+); Anim1.setfillafter (true); switch (state) {case NONE: Arrow.clearanimation (); toppadding (-headerheight); Break;case PULL:arrow.setVisibility (view.visible); Progress.setvisibility (View.gone); Tip.settext ("Pull down to refresh! "); Arrow.clearanimation (); arrow.setanimation (ANIM1); Break;case RELESE:arrow.setVisibility (view.visible); Progress.setvisibility (View.gone); Tip.settext ("Release can be refreshed! "); Arrow.clearanimation (); arrow.setanimation (anim); break;case reflashing:toppadding (); Arrow.setvisibility ( View.gone);p rogress.setvisibility (view.visible); Tip.settext ("refreshing ..."); Arrow.clearanimation (); break;}} /** * get finished data; */public void Reflashcomplete () {//Restores the refresh state to a normal state = none;//Restore state Isremark = False;reflashviewbystate (); TextView lastupdatetime = (TextView) Header.findviewbyid (r.id.lastupdate_time); SimpleDateFormat format = new SimpleDateFormat ("yyyy mm month DD Day HH:MM:SS");D ate date = new Date (System.currenttimemillis ()) ; String time = Format.format (date); Lastupdatetime.settext (TiMe);} public void Setinterface (Ireflashlistener ireflushlistener) {this.ireflushlistener = Ireflushlistener;} /** * Refresh Data interface * @author Administrator */public interface ireflashlistener{public void Onreflush ();}}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Drop-down Refresh (ii)

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.