Android practice simple tutorial-54th gun (pull-down refresh by implementing the OnScrollListener Interface), androidlistener

Source: Internet
Author: User
Tags gety

Android practice simple tutorial-54th gun (pull-down refresh by implementing the OnScrollListener Interface), androidlistener

In the previous article, a simple tutorial on Android-53rd gun (more functions are loaded by OnScrollListener) describes how to implement more functions. In this article, we implemented the pull-down refresh function based on the previous article. This function is mainly implemented through rolling status and gesture listening. Let's take a look at the code below:

1. header. xml:

<? 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" android: paddingBottom = "10dip" android: paddingTop = "10dip"> <LinearLayout android: id = "@ + id/layout" android: layout_width = "wrap_content" Android: layout_height = "wrap_content" android: layout_centerInParent = "true" android: gravity = "center" android: orientation = "vertical"> <TextView android: id = "@ + id/tip" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "pull-down list to refresh! "/> <TextView android: id =" @ + id/lastupdate_time "android: layout_width =" wrap_content "android: layout_height =" wrap_content "/> </LinearLayout> <ImageView android: id = "@ + id/arrow" android: layout_width = "wrap_content" android: 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 =" @ id/layout "android: layout_marginRight =" 20dip "android: visibility = "gone"/> </RelativeLayout> </LinearLayout>

2. LoadListView. java:

Package com. example. listviewscrolldemo; 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. w Idget. absListView. onScrollListener; import android. widget. imageView; import android. widget. listView; import android. widget. progressBar; import android. widget. textView; public class LoadListView extends ListView implements OnScrollListener {private int lastVisibleItem; // The last visible item private int totalItems; // All items private int firstVisibleItem; // The first visible item is private View footer and header; // The bottom layout is private Boolean isLoading. = False; private Boolean isRemark = false; // judge and drop at the top of the current page; private int startY; // Y coordinate value: private ILoadListener iListener; private RLoadListener rListener; private int scrollState; // The current rolling state; global variable private int headerHeight; // the height of the top layout file; final int NONE = 0; // the normal state; final int PULL = 1; // The system prompts the drop-down status; final int RELESE = 2; // The system prompts the release status; final int REFLASHING = 3; // The system refreshes the status; private int state; // judge the current state public LoadListView (Context Context) {super (context); initView (context);} public LoadListView (Context context, AttributeSet attrs) {super (context, attrs); initView (context );} public LoadListView (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr); initView (context );} /*** Add the bottom loading prompt to layout Listview ** @ param context */private void initView (Context context) {LayoutInflater inflater = LayoutInflate R. from (context); footer = inflater. inflate (R. layout. footer, null); header = inflater. inflate (R. layout. header_layout, null); footer. findViewById (R. id. ll_footer ). setVisibility (View. GONE); // first, set the loading prompt to be invisible: measureView (header); headerHeight = header. getMeasuredHeight (); Log. I ("tag", "headerHeight =" + headerHeight); topPadding (-headerHeight); this. addFooterView (footer); this. addHeaderView (header); this. setOnScrol LListener (this); // set the scroll listener}/*** notification parent layout, occupied width and height; ** @ param view */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);} int width = ViewGroup. getChildMeasureSpec (0, 0, p. width); int height; int tempHeight = p. height; if (tempHeight> 0) {height = Mea SureSpec. makeMeasureSpec (tempHeight, MeasureSpec. EXACTLY);} else {height = MeasureSpec. makeMeasureSpec (0, MeasureSpec. UNSPECIFIED);} view. measure (width, height);}/*** sets the header layout top margin; ** @ param topPadding */private void topPadding (int topPadding) {header. setPadding (header. getPaddingLeft (), topPadding, header. getPaddingRight (), header. getPaddingBottom (); header. invalidate () ;}@ Overridepublic void o NScrollStateChanged (AbsListView view, int scrollState) {this. scrollState = scrollState; if (lastVisibleItem = totalItems & scrollState = SCROLL_STATE_IDLE) {if (! IsLoading) {// judge if it is not loading! Footer. findViewById (R. id. ll_footer ). setVisibility (View. VISIBLE); // first, set the loading prompt to display the iListener. onLoad (); isLoading = true ;}}@ Overridepublic void onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {this. lastVisibleItem = firstVisibleItem + visibleItemCount; this. totalItems = totalItemCount; this. firstVisibleItem = firstVisibleItem;} // pass public void setInterface (ILoadLis Tener iListener) {this. iListener = iListener;} public void setRefreshInterface (RLoadListener rListener) {this. rListener = rListener;}/*** callback interface for loading more data ** @ author Administrator **/public interface ILoadListener {public void onLoad ();} /*** pull-down refresh callback interface ** @ author Administrator **/public interface RLoadListener {public void onRefresh ();} // public void loadCompleted () after loading () {isLoading = false; footer. fin DViewById (R. id. ll_footer ). setVisibility (View. GONE) ;}@ Overridepublic boolean onTouchEvent (MotionEvent ev) {// TODO Auto-generated method stubswitch (ev. getAction () {case MotionEvent. ACTION_DOWN: // drop-down if (firstVisibleItem = 0) {isRemark = true; startY = (int) ev. getY ();} break; case MotionEvent. ACTION_MOVE: // move onMove (ev); break; case MotionEvent. ACTION_UP: // pull up if (state = RELESE) {state = REFLASHING; // Add Load the latest data; reflashViewByState (); rListener. onRefresh () ;}else if (state = PULL) {state = NONE; isRemark = false; reflashViewByState () ;}break;} return super. onTouchEvent (ev);}/*** determines the operation of the moving process; ** @ param ev */private void onMove (MotionEvent ev) {if (! IsRemark) {return;} int tempY = (int) ev. getY (); int space = tempY-startY; int topPadding = space-headerHeight; switch (state) {case NONE: if (space> 0) {// slide down state = PULL; reflashViewByState () ;}break; case PULL: topPadding (topPadding); if (space> headerHeight + 30 & scrollState = SCROLL_STATE_TOUCH_SCROLL) {// if you are switching over 30 state = RELESE; reflashViewByState () ;}break; case RELESE: topPadding (topPadding ); If (space 

Here we define four states:

Final int NONE = 0; // normal state;
Final int PULL = 1; // The drop-down status is displayed. (The drop-down distance is short, so release the file without refreshing)
Final int RELESE = 2; // The release status prompt is displayed. (the pull-down distance is long, and the refresh is released at this time)
Final int REFLASHING = 3; // refresh status; (release status, refreshing)

These four States determine the different display effects of the header layout, which is implemented by the reflashViewByState () method.

The onMove () method converts the four States by judging the movement process.

Package com. example. listviewscrolldemo; import java. util. arrayList; import java. util. list; import com. example. listviewscrolldemo. loadListView. ILoadListener; import com. example. listviewscrolldemo. loadListView. RLoadListener; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. widget. arrayAdapter; public class MainActivity extends Activity implements ILoadListener, RLoadListener {private LoadListView mListView; private ArrayAdapter <String> adapter; private List <String> datas; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initViews (); initDatas ();} private void initDatas () {for (int I = 1; I <21; I ++) {datas. add ("data" + I + "") ;}} private void initMoreDatas () {for (int I = 1; I <3; I ++) {datas. add ("new data" + I + "") ;}} private void initViews () {mListView = (LoadListView) findViewById (R. id. lv_main); mListView. setInterface (this); mListView. setRefreshInterface (this); datas = new ArrayList <String> (); adapter = new ArrayAdapter <String> (MainActivity. this, android. r. layout. simple_list_item_1, datas); // adapter = new // ArrayAdapter <String> (MainActivity. this, android. r. layout. simple_list_item_1); mListView. setAdapter (adapter) ;}@ Overridepublic void onLoad () {// Add the latency effect Handler handler = new Handler (); handler. postDelayed (new Runnable () {public void run () {initMoreDatas (); // get more data adapter. notifyDataSetChanged (); // refresh ListViewmListView. loadCompleted (); // hide the loading prompt }}, 2000) ;}@ Overridepublic void onRefresh () {// Add the delayed effect Handler handler = new Handler (); handler. postDelayed (new Runnable () {public void run () {initRefreshDatas (); // get more data adapter. notifyDataSetChanged (); // refresh ListViewmListView. reflashComplete (); // hide the refresh prompt }}, 2000);} private void initRefreshDatas () {// datas. add ("new data" + I + ""); datas. add (0, "pull-down refresh data" + 1 + "); // This method inserts the header datas. add (0, "pull-down and refresh data" + 2 + "");}}

Run the following instance:


By then, both the pull-up and pull-down functions will be implemented.

Follow me to your favorite friends! Thank you.

Source code download



Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.