Android custom Control Drop-down Refresh Instance code _android

Source: Internet
Author: User

Implementation effect:

Picture material:

--> first, write down the refresh layout when you refresh Pull_to_refresh.xml:

<resources> <string name= "app_name" >PullToRefreshTest</string> <string name= "Pull_to_refresh" > dropdown can refresh </string> <string name= "Release_to_refresh" > Release immediately refresh </string> <string name= " Refreshing "> is refreshing ...</string> <string name=" Not_updated_yet "> has not been updated </string> <string name=" Updated_at "> Last updated on%1 $ s </string> <string name=" Updated_just_now "> Just updated </string> <string name = "Time_error" > Time problem </string> </resources> <?xml version= "1.0" encoding= "Utf-8"?> <
  Relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:id= "@+id/pull_to_refresh_head" Android:layout_width= "Match_parent" android:layout_height= "60DP" > <linearlayout android:layout_width= "200dp "Android:layout_height=" 60DP "android:layout_centerinparent=" true "android:orientation=" Horizontal "> & Lt Relativelayout android:layout_width= "0DP" android:layout_height= "60DP" android:layout_weight= "3" > <imageview android:id= "@+id/arrow" Android:lay
        Out_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_centerinparent= "true" android:src= "@mipmap/indicator_arrow"/> <progressbar android:id= "@+id/progress_bar" Android: Layout_width= "30DP" android:layout_height= "30DP" android:layout_centerinparent= "true" Android:visi bility= "Gone"/> </RelativeLayout> <linearlayout android:layout_width= "0DP" android:layout _height= "60DP" android:layout_weight= "android:orientation=" "vertical" > <textview androi D:id= "@+id/description" android:layout_width= "match_parent" android:layout_height= "0DP" Android:la
      yout_weight= "1" android:gravity= "Center_horizontal|bottom" android:text= "@string/pull_to_refresh"/>
       <textview Android:id= "@+id/updated_at" android:layout_width= "match_parent" android:layout_height= "0DP" Andr
    oid:layout_weight= "1" android:gravity= "Center_horizontal|top" android:text= "@string/updated_at"/> </LinearLayout> </LinearLayout> </RelativeLayout>
Strings Pull_to_refresh--> Then, is also the main, custom Drop-down refresh View (contains drop-down refresh all operations) RefreshView.java:package Com.dragon.android.tofres
Hlayout;
Import Android.content.Context;
Import android.content.SharedPreferences;
Import Android.os.AsyncTask;
Import Android.os.SystemClock;
Import Android.preference.PreferenceManager;
Import Android.util.AttributeSet;
Import Android.view.LayoutInflater;
Import android.view.MotionEvent;
Import Android.view.View;
Import android.view.ViewConfiguration;
Import android.view.animation.RotateAnimation;
Import Android.widget.ImageView;
Import Android.widget.LinearLayout;
Import Android.widget.ListView;
Import Android.widget.ProgressBar;
Import Android.widget.TextView; public class Refreshview extends LinearLayout implements View.ontouchlistener {private static final String TAG = REFRESHV
Iew.class.getSimpleName (); public enum Pull_status {status_pull_to_refresh (0),//dropdown state Status_release_to_refresh (1),//release immediate refresh status status_refreshing (2),//Is refreshing state status_refresh_finished (3); Refresh completed or not refreshed status private int status;
State pull_status (int value) {this.status = value;} public int getValue () {return this.status;}}
The speed of the Drop-down head rollback is public static final int scroll_speed =-20;
A minute millisecond value that is used to determine the last update time public static final long One_minute = 60 * 1000;
The millisecond value of one hour to determine the last update time public static final long one_hour = One_minute;
The millisecond value of the day, used to determine the last update time public static final long one_day = * One_hour;
The January millisecond value used to determine the last update time public static final long one_month = * ONE_DAY;
A one-year millisecond value used to determine the last update time public static final long one_year = One_month;
string constant for the last update time, used as the Sharedpreferences key value private static final string updated_at = "Updated_at";
Dropdown Flush Callback Interface private Pulltorefreshlistener Mlistener; Private sharedpreferences preferences; Used to store the private View header for the last update time; View private ListView ListView of the dropdown head; Need to go down-pull refreshed listview private ProgressBar ProgressBar; Progress bar displayed when refreshing private ImageView arrow; Instructions for pulling down and releasing arrows private TextView description; Indicates the dropdown and release of the text description private TextView updAteat; The text description of the last update time private marginlayoutparams headerlayoutparams; The layout parameter of the Drop-down head is private long lastupdatetime;
The millisecond value of the last update//To prevent drop-down refreshes of different interfaces from conflicting with each other during the last update time, use IDs to differentiate private int mId =-1; private int hideheaderheight; The height of the drop head/** * What state is currently being processed, optional values are Status_pull_to_refresh, Status_release_to_refresh, status_refreshing and Status_refresh_ Finished * * Private pull_status Currentstatus = Pull_status.
status_refresh_finished;
Record what the last state is, avoid repetitive operations private pull_status laststatus = Currentstatus; private float Ydown; Finger press when the screen ordinate private int touchslop;
The maximum value that the user's finger can move before being judged to be scrolled. Private Boolean loadonce; Whether the layout has been loaded once, where initialization in onlayout only needs to be loaded once private Boolean abletopull; Whether the current can be pulled down, only ListView scroll to the end of the Allow Drop-down/** * Drop-down to refresh the control's constructor, will dynamically add a drop-down at runtime layout/public Refreshview
AttributeSet attrs) {Super (context, attrs); preferences = preferencemanager.getdefaultsharedpreferences (context);
Header = Layoutinflater.from (context). Inflate (R.layout.pull_to_refresh, NULL, TRUE); ProgressBar = (ProgressBar) Header.findviewbyid (R.id.progress_bar);
Arrow = (ImageView) Header.findviewbyid (R.id.arrow);
Description = (TextView) Header.findviewbyid (r.id.description);
Updateat = (TextView) Header.findviewbyid (R.ID.UPDATED_AT);
Touchslop = Viewconfiguration.get (context). Getscaledtouchslop ();
Refreshupdatedatvalue ();
SetOrientation (VERTICAL);
AddView (header, 0);
LOG.D (TAG, "Refreshview constructor () getchildat (0):" + getchildat (0));
LOG.D (TAG, "Refreshview constructor () getchildat (0):" + getchildat (1));
ListView = (ListView) getchildat (1);
Listview.setontouchlistener (this); /** * Perform some critical initialization operations, such as: Pull down the head up to hide, give ListView registered touch Event/@Override protected void OnLayout (Boolean changed, int l, int T, int r, int b) {super.onlayout (changed, L, T, R, b); if (changed &&!loadonce) {hideheaderheight =-header
. GetHeight ();
Headerlayoutparams = (marginlayoutparams) header.getlayoutparams ();
Headerlayoutparams.topmargin = Hideheaderheight;
ListView = (ListView) getchildat (1); //LOG.D (TAG, "OnLayout () getchildat (0):" + getchildat (0));
LOG.D (TAG, "OnLayout () ListView:" + ListView);
Listview.setontouchlistener (this);
Loadonce = true; }/** * When ListView is touched, it handles various Drop-down refresh specific logic */@Override public boolean Ontouch (View V, motionevent event) {Setcanableto Pull (event); Determine whether you can drop if (abletopull) {switch (event.getaction ()) {Case MotionEvent.ACTION_DOWN:yDown = Event.getrawy ();
ASE Motionevent.action_move://Get position of the Y axis in move float Ymove = Event.getrawy ();
Gets the distance moved from press to move int distance = (int) (ymove-ydown); If the finger is up-sliding and the drop-head is completely hidden, disable the drop down event if (distance <= 0 && headerlayoutparams.topmargin <= hideheaderheight) {R
Eturn false; } if (distance < Touchslop) {return false;}//Determine if the Refresh state if (Currentstatus!= pull_status.
status_refreshing) {//TopMargin whether the setting is > 0, the default initial setting is-header.getheight () if (Headerlayoutparams.topmargin > 0) { Currentstatus = Pull_status.
Status_release_to_refresh; else {//otherwise status is currentstatus in dropdown =Pull_status.
Status_pull_to_refresh;
///Through the offset of the topMargin value of the drop-down, to achieve the pull effect Headerlayoutparams.topmargin = (DISTANCE/2) + hideheaderheight;
Header.setlayoutparams (Headerlayoutparams);
} break; Case MotionEvent.ACTION_UP:default:if (Currentstatus = = Pull_status. Status_release_to_refresh) {//When releasing the immediately refreshed state, call the task New Refreshingtask () that is being refreshed. Execute ();} else if (Currentstatus = PU Ll_status.
Status_pull_to_refresh) {//If it is a drop-down state, call the hidden Drop-down task New Hideheadertask (). Execute (); //Always remember to update the information in the dropdown header if (Currentstatus = = Pull_status. Status_pull_to_refresh | | Currentstatus = = Pull_status.
Status_release_to_refresh) {Updateheaderview ()/////////////////////////////////////////
Listview.setpressed (FALSE);
Listview.setfocusable (FALSE);
Listview.setfocusableintouchmode (FALSE);
Laststatus = Currentstatus;
is currently in a drop-down or release state, masking the ListView scrolling event return true by returning true;
return false; /** * to the Drop-down Refresh control register a listener * * @param listener Listener Implementation * @param ID in order to prevent different interface of the Drop-down refresh in the last update time conflict, the different interface in the registration Drop-down Refresh listener when aSet to pass in a different ID/public void Setonrefreshlistener (Pulltorefreshlistener listener, int id) {Mlistener = listener; mId = ID;} /** * When all the refresh logic is complete, the record is called, otherwise your ListView will be in the refresh State/public void finishrefreshing () {currentstatus = Pull_status.
status_refresh_finished;
Preferences.edit (). Putlong (Updated_at + mId, System.currenttimemillis ()). commit ();
New Hideheadertask (). Execute (); /** * According to the current ListView scrolling state to set the {@link #ableToPull} * value, each need to be in the first execution in Ontouch, so that you can determine whether the current should be rolling ListView, or should be carried out under the pull * * private void Setcanabletopull (Motionevent event) {View FirstChild = listview.getchildat (0); if (firstchild!= null) {//Get LISTV
The position of the first item in the iew int firstvisiblepos = Listview.getfirstvisibleposition (); Determines whether top of the first child control is equal to the first Item position if (firstvisiblepos = 0 && firstchild.gettop () = = 0) {if (!abletopull) {//GE
Trawy () obtains a position relative to the Y direction of the screen Ydown = Event.getrawy ();
//If the top edge of the first element, the distance from the parent layout value is 0, the ListView scroll to the top, and the drop-down should be allowed to refresh Abletopull = true; else {if (Headerlayoutparams.topmargin!= hideheaderHeight) {headerlayoutparams.topmargin = Hideheaderheight; Header.setlayoutparams (headerlayoutparams);} ableToPull =
False
} else {//If there are no elements in the ListView, you should also allow Drop-down refresh Abletopull = true;} /** * Update the information in the Drop-down header/private void Updateheaderview () {if (laststatus!= currentstatus) {if (Currentstatus = = PULL_STATUS.S
Tatus_pull_to_refresh) {Description.settext (Getresources (). getString (R.string.pull_to_refresh));
Arrow.setvisibility (view.visible);
Progressbar.setvisibility (View.gone);
Rotatearrow (); else if (Currentstatus = Pull_status.
Status_release_to_refresh) {Description.settext (Getresources (). getString (R.string.release_to_refresh));
Arrow.setvisibility (view.visible);
Progressbar.setvisibility (View.gone);
Rotatearrow (); else if (Currentstatus = Pull_status.
status_refreshing) {Description.settext (Getresources (). getString (r.string.refreshing));
Progressbar.setvisibility (view.visible);
Arrow.clearanimation ();
Arrow.setvisibility (View.gone);
} refreshupdatedatvalue (); }/** * According to the current shapeState to rotate the arrow */private void Rotatearrow () {Float pivotx = arrow.getwidth ()/2f; float Pivoty = Arrow.getheight ()/2f; float
Fromdegrees = 0f;
float todegrees = 0f; if (Currentstatus = = Pull_status. Status_pull_to_refresh) {fromdegrees = 180f; todegrees = 360f;} else if (Currentstatus = = Pull_status.
Status_release_to_refresh) {fromdegrees = 0f; todegrees = 180f;}
rotateanimation animation = new Rotateanimation (fromdegrees, Todegrees, Pivotx, Pivoty);
Animation.setduration (100);
Animation.setfillafter (TRUE);
Arrow.startanimation (animation);  /** * Refresh the text description of the last update time in the Drop-down header/private void Refreshupdatedatvalue () {lastupdatetime = Preferences.getlong (Updated_at + mId,
-1);
Long currenttime = System.currenttimemillis ();
Long timepassed = Currenttime-lastupdatetime;
Long Timeintoformat;
String Updateatvalue;  if (LastUpdateTime = = 1) {Updateatvalue = Getresources (). getString (R.string.not_updated_yet);} else if (Timepassed < 0) {Updateatvalue = Getresources (). getString (R.string.time_error); else if (timepassed < One_minute) {Updateatvalue = Getresources (). getString (R.string.updated_just_now);} else if (t
imepassed < One_hour) {Timeintoformat = Timepassed/one_minute;
String value = Timeintoformat + "Minutes";
Updateatvalue = String.Format (Getresources (). getString (R.string.updated_at), value);
else if (timepassed < one_day) {Timeintoformat = Timepassed/one_hour;
String value = Timeintoformat + "Hour";
Updateatvalue = String.Format (Getresources (). getString (R.string.updated_at), value);
else if (timepassed < one_month) {Timeintoformat = Timepassed/one_day;
String value = Timeintoformat + "Days";
Updateatvalue = String.Format (Getresources (). getString (R.string.updated_at), value);
else if (timepassed < one_year) {Timeintoformat = Timepassed/one_month;
String value = Timeintoformat + "month";
Updateatvalue = String.Format (Getresources (). getString (R.string.updated_at), value);
else {timeintoformat = timepassed/one_year; String value = Timeintoformat + "Year";
Updateatvalue = String.Format (Getresources (). getString (R.string.updated_at), value);
} updateat.settext (Updateatvalue); /** * is refreshing the task, in this task will be callback registered in the Drop-down Refresh listener * * Class Refreshingtask extends Asynctask<void, Integer, void> {@Override Pro tected void Doinbackground (void ... params) {int topMargin = Headerlayoutparams.topmargin; while (true) {TopMargin = topm
Argin + scroll_speed;
if (topMargin <= 0) {topMargin = 0; break;} publishprogress (TopMargin);
Systemclock.sleep (10); } currentstatus = Pull_status.
status_refreshing;
Publishprogress (0);
if (Mlistener!= null) {Mlistener.onrefresh ();} return null; } @Override protected void Onprogressupdate (Integer ... topMargin) {Updateheaderview (); headerlayoutparams.topmargin =
TOPMARGIN[0];
Header.setlayoutparams (Headerlayoutparams);  }/** * Hides the task of the Drop-down header, this task will cause the dropdown head to be hidden again/class Hideheadertask extends Asynctask<void, Integer, integer> when no drop-down refresh or Drop-down refresh is complete {@Override protected Integer doinbackground (Void ... params) {int Topmargin = headerlayoutparams.topmargin; 
while (true) {TopMargin = TopMargin + scroll_speed; if (TopMargin <= hideheaderheight) {topMargin = Hideheaderheight;
Break
} publishprogress (TopMargin);
Systemclock.sleep (10);
return topMargin; @Override protected void Onprogressupdate (Integer ... topMargin) {headerlayoutparams.topmargin = topmargin[0]; header.
Setlayoutparams (Headerlayoutparams);
} @Override protected void OnPostExecute (Integer topMargin) {headerlayoutparams.topmargin = TopMargin;
Header.setlayoutparams (Headerlayoutparams); Currentstatus = Pull_status.
status_refresh_finished; }/** * Drop-down refresh listener, use drop down refresh place should register this listener to get refresh callback/public interface Pulltorefreshlistener {//refresh will go back to this method, write specific refresh logic in the method.
Note that this method is invoked in a child thread, and that you do not have to have a separate thread for time-consuming operations void Onrefresh (); }
}

--> The third step, write the main layout:

<?xml version= "1.0" encoding= "Utf-8"?> <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"
  tools:context= ". Mainactivity ">
  <com.dragon.android.tofreshlayout.refreshview
    android:id=" @+id/refreshable_view "
    android:layout_width= "match_parent"
    android:layout_height= "match_parent" >
    <listview
      Android:id= "@+id/list_view"
      android:layout_width= "match_parent"
      android:layout_height= "Match_parent" >
    </ListView>
  </com.dragon.android.tofreshlayout.RefreshView>
</ Relativelayout>

--> Finally, the Java code adds the ListView data:

Package com.dragon.android.tofreshlayout;
Import Android.os.Bundle;
Import Android.os.SystemClock;
Import android.support.v7.app.AppCompatActivity;
Import Android.webkit.WebView;
Import Android.widget.ArrayAdapter;
Import Android.widget.ListView;
  public class Mainactivity extends appcompatactivity {Refreshview refreshableview;
  ListView ListView;
  Arrayadapter<string> adapter;
  Private WebView WebView;
  private static int NUM = 30;
  string[] items = new String[num];
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Getsupportactionbar (). Hide ();
    for (int i = 0; i < items.length i++) {items[i] = "list item" + I;
    } Refreshableview = (Refreshview) Findviewbyid (R.id.refreshable_view);
    ListView = (ListView) Findviewbyid (R.id.list_view); adapter = new Arrayadapter<> (this, Android.
    R.layout.simple_list_item_1, items); Listview.setadapter (ADAPter); Refreshableview.setonrefreshlistener (New Refreshview.pulltorefreshlistener () {@Override public void Onrefresh
        () {systemclock.sleep (3000);
      Refreshableview.finishrefreshing ();
  }, 0); }
}

Program Demo: Link: http://pan.baidu.com/s/1ge6Llw3 Password: Skna

In fact, it should be encapsulated ... *****************

The above is a small set to introduce the Android custom control Drop-down to refresh the instance code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.