Allow Swiperefreshlayout in Android support V4 to load more

Source: Internet
Author: User

ObjectiveThe original Android SDK does not have a pull-down refresh component, but this component is really a part of most app essentials. Fortunately, Google has a swiperefreshlayout in the V4 package, but this component only supports pull-down refreshes and does not support loading more operations. Therefore, we will simply extend this component to achieve the purpose of pull-up download.
Basic principlepull-up loading or scrolling to the bottom automatically loaded, all by judging whether to scroll to the bottom of the ListView or other view, and then trigger the corresponding action, here we use the ListView to explain. So we need to listen to the scroll events of the ListView and automatically trigger the load when the ListView scrolls to the bottom, but when the user supports the finger to slide the screen without scrolling, we also need to let it load, so this situation is the pull-up load more. So we need to make a judgment in the touch event, if it's at the bottom and the user is a pull-up operation, then load more. time is limited, directly on the code bar. Implementation code
/** * Inherits from the Swiperefreshlayout, thus realizing the pull-up load more functions when sliding to the bottom. * * @author mrsimple */public class Refreshlayout extends Swiperefreshlayout implements Onscrolllistener {/** * slip    Pull-up operation at the bottom of the page */private int mtouchslop;    /** * ListView Instance */Private ListView Mlistview;    /** * Pull-up listener, to the bottom of the pull-up loading operation */private Onloadlistener Monloadlistener;    /** * ListView Loading in Footer */private View mlistviewfooter;    /** * y coordinate when pressed * */private int mydown;    /** * When lifting the y-coordinate, with the mydown used to slide to the bottom of the judgment is pull up or pull down */private int mlasty;    /** * Whether in load (pull up more) */private Boolean isloading = false;    /** * @param context */public refreshlayout (context context) {This (context, NULL);        } public Refreshlayout (context context, AttributeSet Attrs) {Super (context, attrs);        Mtouchslop = Viewconfiguration.get (context). Getscaledtouchslop (); Mlistviewfooter = Layoutinflater.from (context). Inflate (R.layout.listview_footer, NULL, FALSE); } @Override protected void OnLayout (Boolean changed, int left, int top, int. right, int bottom) {Super.onlayo        UT (changed, left, top, right, bottom);        Initializes the ListView object if (Mlistview = = null) {Getlistview ();        }}/** * Gets the ListView object */private void Getlistview () {int childs = Getchildcount ();            if (Childs > 0) {View Childview = getchildat (0);                if (Childview instanceof listview) {Mlistview = (listview) Childview;                Set the scroll listener to the ListView, making it possible to automatically load the Mlistview.setonscrolllistener (this) in the case of scrolling;            LOG.D (View_log_tag, "# # # found the ListView");     }}}//* (non-javadoc) * @see android.view.viewgroup#dispatchtouchevent (android.view.MotionEvent)        */@Override public boolean dispatchtouchevent (Motionevent event) {Final int action = Event.getaction (); Switch (action){Case Motionevent.action_down://press Mydown = (int) Event.getrawy ();            Break                Case Motionevent.action_move://move mlasty = (int) Event.getrawy ();            Break                Case MOTIONEVENT.ACTION_UP://Lift if (canload ()) {loaddata ();            } break;        Default:break;    } return Super.dispatchtouchevent (event);     }/** * Can load more, the condition is at the bottom, the ListView is not loaded, and is a pull-up operation. * * @return * * Private Boolean canload () {return isbottom () &&!isloading && Ispullup (    ); }/** * Determines if it is at the bottom */private Boolean isbottom () {if (Mlistview! = null && mlistview.getadapt        ER () = null) {return mlistview.getlastvisibleposition () = = (Mlistview.getadapter (). GetCount ()-1);    } return false; }    /**     *Whether it is a pull-up operation * * @return */Private Boolean Ispullup () {return (mydown-mlasty) >= mtouchslop;            /** * If it is at the bottom and is a pull-up operation. Then execute the OnLoad method */private void LoadData () {if (Monloadlistener! = null) {            Set state setloading (TRUE);        Monloadlistener.onload ();        }}/** * @param loading */public void setloading (Boolean loading) {isloading = loading;        if (isloading) {Mlistview.addfooterview (mlistviewfooter);            } else {Mlistview.removefooterview (mlistviewfooter);            Mydown = 0;        mlasty = 0; }}/** * @param loadlistener */public void Setonloadlistener (Onloadlistener loadlistener) {monl    Oadlistener = Loadlistener; } @Override public void onscrollstatechanged (Abslistview view, int. scrollstate) {} @Override public void O Nscroll (abslistview view, int firstvisibleitem, int visibleitemCount, int totalitemcount) {//scroll to the very bottom can also load more if (Canload ()) {loaddata (); }}/** * Load more Listeners * * @author mrsimple */public static interface Onloadlistener {Publi    c void OnLoad (); }}

listview_footer.xml:
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" wrap_content "android:background=" @color/umeng _COMM_COMMENTS_BG "android:gravity=" center "android:paddingbottom=" 8dip "android:paddingtop=" 5dip "> &LT;PR Ogressbar android:id= "@+id/pull_to_refresh_load_progress" style= "@android: STYLE/WIDGET.PROGRESSBAR.SMALL.INV Erse "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:layout_centerv Ertical= "true" android:layout_centerhorizontal= "true" android:paddingright= "100DP" android:indetermin Ate= "true"/> <textview android:id= "@+id/pull_to_refresh_loadmore_text" android:layout_width= "Fill_         Parent "android:layout_height=" wrap_content "android:layout_gravity=" center "android:gravity=" center " android:paddingtop= "5dip"        android:text= "@string/load" android:textappearance= "Android:attr/textappearancemedium" Android:text Color= "@android: Color/darker_gray" android:textsize= "14sp" android:textstyle= "bold"/></relativelayout >

Using the exampleRefresh.xml layout file:
<?xml version= "1.0" encoding= "Utf-8"? ><myview. Refreshlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:id= "@+id/swipe_layout"    android:layout_width= "match_parent"    android:layout_height= "match_parent" >    <listview        Android:id= "@+id/listview"        android:layout_width= "match_parent"        android:layout_height= "Match_parent" >    </listview></myview. Refreshlayout>

Use in activity:
/** * @author mrsimple */public class Mainactivity extends Activity {@Override protected void onCreate (Bundle saved          Instancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.refresh);        Simulate some data final list<string> datas = new arraylist<string> ();        for (int i = 0; i <; i++) {Datas.add ("item-" + i); }//Fabric Adapter Final Baseadapter adapter = new Arrayadapter<string> (this, Android.        R.layout.simple_list_item_1, datas);        Gets the ListView instance of the ListView ListView = (ListView) Findviewbyid (R.id.listview);        Listview.setadapter (adapter); Get Refreshlayout instance final refreshlayout Myrefreshlistview = (refreshlayout) Findviewbyid (r.id.swipe        _layout); Sets the color value when the drop-down is refreshed, and the color value needs to be defined in the XML Myrefreshlistview. SetColorScheme (R.color.umeng_comm_text_topic_light_co Lor, R.color.umeng_Comm_yellow, R.color.umeng_comm_green, R.color.umeng_comm_linked_text); Set the drop-down Refresh listener Myrefreshlistview.setonrefreshlistener (new Onrefreshlistener () {@Override publi                c void Onrefresh () {Toast.maketext (mainactivity.this, "Refresh", Toast.length_short). Show ();                        Myrefreshlistview.postdelayed (New Runnable () {@Override public void run () {                        Update Data Datas.add (new Date (). togmtstring ());                        Adapter.notifydatasetchanged ();                    Call the method end Refresh Myrefreshlistview.setrefreshing (false) after the update is complete;            }}, 1000);        }        }); Load Listener Myrefreshlistview.setonloadlistener (new Onloadlistener () {@Override public void OnL Oad () {Toast.maketext (mainactivity.this, "load", Toast.length_short). Show();                        Myrefreshlistview.postdelayed (New Runnable () {@Override public void run () {                        Datas.add (New Date (). togmtstring ());                        Adapter.notifydatasetchanged ();                    Call the method Myrefreshlistview.setloading (false) after the load is finished;            }}, 1500);    }        }); }    }

Allow Swiperefreshlayout in Android support V4 to load more

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.