Android Drop-down Refresh Framework Implementation code Instance _android

Source: Internet
Author: User

The previous period of time projects used in the Drop-down refresh function, before the internet also found similar demo, but the quality of these demos are uneven, user experience is not good, interface design is not. The most is no way, finally can not endure, oneself wrote a drop-down refreshing frame, this framework is a general framework, the effect and design feel good, now share to you reader.

I. About drop-down refresh

Dropdown Refresh This user interaction was first invented by Twitter founder Loren Brichette (Loren Brichter), and there is a theory that a drop-down refresh is a suitable application for arranging feeds in a new to old time sequence, when you see the old content in this scenario, The user will naturally pull down to find the updated content, so the Drop-down refresh is very reasonable. You can refer to this article: An interesting drop-down refresh, below I post an interesting drop-down refresh case.

Figure one, interesting dropdown refresh case (i)
Figure II, interesting dropdown refresh case (ii)

Two. Principle of realization

The above examples, the appearance of a good look, he is essentially the same, that is a drop-down refresh control usually consists of the following parts:

"1" Header

Header usually has a drop-down arrow, text, progress bar and other elements, depending on the distance to the drop to change its state, so as to show different styles

"2" Content

This part is the content area, there are many examples of the Internet is directly in the ListView add header, but this has limitations, because many cases do not necessarily use ListView to display data. We put the view to display content in one of our containers, and if you want to implement a Drop-down refresh with listview display data, you need to create a ListView to rotate into my container. We deal with this container's events (down, moves, up), and if you pull down, slide the entire layout down to show the header.

"3" Footer

Footer can be used to show arrows pulling up, automatically loading more progress bars, and so on.

The above three-part summary is the layout structure shown in the following figure:

Figure three, the layout structure of the Drop-down refresh

For the above illustration, a few points need to be explained:

1, this layout expands in the linearlayout, the vertical arrangement

2, from top to bottom of the order is: Header, Content, Footer

3, content filled with the parent control, by setting top, bottom padding to make header and footer invisible, that is, let it out of the screen

4, drop down, call the Scrollto method to slide the entire layout down, so that the header display, pull up just the opposite of the Drop-down.

5. The derived class needs to be implemented by populating the content view into the parent container, for example, if you want to use it, then you need to add ListView, ScrollView, WebView, etc. to the container.

6, the red area above is the size of the screen (strictly speaking, the screen size is not accurate, it should be said to be more accurate content area)

Three. Concrete implementation

Understand the implementation of the principle and process, we try to concrete implementation, first of all, in order to better expand later, the design more reasonable, we have to pull down the function of refreshing to abstract into an interface:
1, ipulltorefresh<t extends view>

It is specifically defined by the following methods:

Public interface Ipulltorefresh<t extends view> {public 
  void setpullrefreshenabled (Boolean pullrefreshenabled); 
  public void Setpullloadenabled (Boolean pullloadenabled); 
  public void Setscrollloadenabled (Boolean scrollloadenabled); 
  public boolean ispullrefreshenabled (); 
  public boolean ispullloadenabled (); 
  public boolean isscrollloadenabled (); 
  public void Setonrefreshlistener (onrefreshlistener<t> refreshlistener); 
  public void Onpulldownrefreshcomplete (); 
  public void Onpulluprefreshcomplete (); 
  Public T Getrefreshableview (); 
  Public Loadinglayout getheaderloadinglayout (); 
  Public Loadinglayout getfooterloadinglayout (); 
  public void Setlastupdatedlabel (Charsequence label); 
} 

This interface is a generic, and it accepts the derived class of view, because is not a view to be placed in our container?

2, Pulltorefreshbase<t extends view>

This class implements the Ipulltorefresh interface, which is inherited from LinearLayout, as an abstract base class for Drop-down refreshes, and if you want to implement ListView Drop-down refreshes, just extend the class and implement some of the necessary methods. The responsibilities of this class are mainly as follows:

    • Handling events in Onintercepttouchevent () and Ontouchevent (): When the content view (such as ListView) is at the top, and then down again, we have to truncate the event, The move event then passes the subsequent events to the Ontouchevent () method, and then in this method, we scroll the entire view according to the move distance.
    • Responsible for creating headers, footer, and content view: calling methods in the constructor to create View of these three parts, derived classes can override these methods to provide header and footer of different styles, It calls the Createheaderloadinglayout and Createfooterloadinglayout methods to create headers and footer The method of creating content view is an abstract method that must be implemented by a derived class. Returns a non-null view, and then the container adds the view to itself.
    • To set various states: There are many states in this, such as pull, Oberra, refresh, load, release, etc., it will be based on the user pull distance to change the state, the state of change, it will be the header and footer state changes, and then header and footer according to the state to show the corresponding interface style.

3, Pulltorefreshbase<t extends view> inheritance relationship

Here I have implemented three derived classes of Drop-down refreshes, namely ListView, ScrollView, WebView Three, whose inheritance relationships are as follows:

Diagram Iv. inheritance relationships of pulltorefreshbase classes

There are several points to note about the Pulltorefreshbase class and its pies and classes:

For Listview,scrollview,webview in these three cases, whether they slide to the top or bottom of the implementation is not the same, so in the Pulltorefreshbase class you need to call two abstract methods to determine whether the current position is at the top or bottom, and its derived classes must implement both methods. For example, for ListView, it slides to the top of the condition that the first child is fully visible and that primary postion is 0. These two abstract methods are:

/** 
 * Determines whether the refreshed view slides to the top 
 * 
 * @return True indicates that the top has been slid, otherwise false/ 
protected Abstract Boolean Isreadyforpulldown (); 
 
/** 
 * To determine if the refreshed view is sliding to the end 
 * 
 @return True indicates that it has slipped to the bottom, or false 
  

An abstract way to create a view (that is, content view) that can be pulled down and refreshed is

/** 
 * Create a refreshed view 
 * * 
 @param context 
 * @param attrs Properties 
 * @return View 
/ Protected abstract T Createrefreshableview (context context, attributeset attrs); 

4, Loadinglayout

Loadinglayout is an abstraction of the refresh layout, which is an abstract base class. Headers and footer are all extended to this class. This class of abstract classes provides two abstract methods:

Getcontentsize

This method returns the current size of the refresh layout, usually returning the height of the layout, so that the method name does not take Getlayoutheight () and so on, so that the return value will be the threshold that can be refreshed after the drop. If the Drop-down offset value is greater than this value, it is assumed that it can be refreshed or not refreshed, and this method must be implemented by a derived class.

SetState

This method is used to set the state of the current refresh layout, the Pulltorefreshbase class will call this method, when the move into the Drop-down, let go, and so on, will call this method, the derived class only to be based on these states to achieve a different interface display, the following pull state, the display of arrows, When the state is refreshed, the loading icon is displayed.

Possible status values are: RESET, Pull_to_refresh, Release_to_refresh, refreshing, no_more_data

The inheritance relationship of Loadinglayout and its derived classes is shown in the following illustration:

Diagram five, loadinglayout and their derived classes

We are free to make our own headers and footer, and we can also implement headers and footer in the various Drop-down refresh cases shown in figure I and figure II, as long as the two methods Getcontentsize () and SetState () are rewritten. Headerloadinglayout, which defaults to the layout of the arrow style, and rotateloadinglayout is the style that displays a rotating icon.

5. Event handling

We must rewrite the Pulltorefreshbase class's two event-related methods Onintercepttouchevent () and Ontouchevent () methods. Because Listview,scrollview,webview they are placed inside the Pulltorefreshbase, the event is first passed to the Pulltorefreshbase#onintercepttouchevent () method, So we should deal with the Action_move event in this method to determine if the current Listview,scrollview,webview is at the top or bottom, and if so, start truncating the event, and once the event is truncated, Subsequent events are passed to the Pulltorefreshbase#onintercepttouchevent () method, where we then move the entire layout in the Action_move event to implement the pull or pull action.

6. Rolling layout (Scrollto)

As you can see in the layout structure of figure three, headers and footer are placed at the top and bottom of the content view by default, and set padding to let him run out of the screen, if we scroll down the entire layout (Scrollto) a certain distance, Then the header will be displayed, based on this situation, so in my implementation, I finally call Scrollto to implement the Drop-down action.

In general, the implementation of important points on these, specific details in the implementation will encounter a lot, you can refer to the code.

Four. How to use

Use the Drop-down refresh code as follows

@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Mpulllistview = new Pulltorefreshlistview (this); 
     
    Setcontentview (Mpulllistview); 
    Mpulllistview.setpullloadenabled (FALSE) is not available on pull load; 
     
    Scroll in the end to automatically load available mpulllistview.setscrollloadenabled (true); 
    Mcurindex = Mloaddatacount; 
    Mlistitems = new linkedlist<string> (); 
    Mlistitems.addall (Arrays.aslist (mstrings). sublist (0, Mcurindex)); Madapter = new Arrayadapter<string> (this, Android. 
     
    R.layout.simple_list_item_1, Mlistitems); 
    Get the actual listview Mlistview = Mpulllistview.getrefreshableview ();     
    Binding Data Mlistview.setadapter (Madapter); 
      Sets the Listener Mpulllistview.setonrefreshlistener (new onrefreshlistener<listview> () {@Override for the Drop-down refresh 
        public void Onpulldowntorefresh (pulltorefreshbase<listview> refreshview) {Misstart = true; New Getdatatask (). exeCute (); @Override public void Onpulluptorefresh (pulltorefreshbase<listview> refreshview) {Missta 
        RT = FALSE; 
      New Getdatatask (). Execute (); 
    } 
    }); 
     
    Setlastupdatetime (); 
  Automatic refresh Mpulllistview.dopullrefreshing (true, 500); 
 }

This is the layout that initializes a drop-down refresh and calls Setcontentview to set to the activity.

After the Drop-down refresh is complete, we can call the Onpulldownrefreshcomplete () and Onpulluprefreshcomplete () methods to stop the refresh and load

Five. Operation effect
Here is a list of the demo's running effect chart.

Figure VI, ListView drop-down Refresh, note header and footer style

Six. Bug fixes

Known bug fixes are as follows, found the code bug Reader can also give me feedback, thank you ~ ~ ~

1, for ListView Drop-down Refresh, when scrolling is enabled to automatically load, if the footer changed from hidden to display, show an exception
This problem has been fixed and the revised code is as follows:

Pulltorefreshlistview#setscrollloadenabled method, the revised code is as follows:
@Override public 
void setscrollloadenabled ( Boolean scrollloadenabled) { 
  if (isscrollloadenabled () = = scrollloadenabled) {return 
    ; 
  } 
   
  Super.setscrollloadenabled (scrollloadenabled); 
   
  if (scrollloadenabled) { 
    //Set footer 
    if (null = = Mloadmorefooterlayout) { 
      mloadmorefooterlayout = new Footerloadinglayout (GetContext ()); 
      Mlistview.addfooterview (Mloadmorefooterlayout, NULL, FALSE); 
    } 
     
    Mloadmorefooterlayout.show (true); 
  else { 
    if (null!= mloadmorefooterlayout) { 
      mloadmorefooterlayout.show (false); 
    } 
  } 
} 

Loadinglayout#show method, the revised code is as follows:

/** 
 * Shows or hides this layout 
 * * 
 @param show flag */public void show 
 (a 
) { 
  //If is showing, do Noth Ing. 
  if (show = = (View.visible = = Getvisibility ())) {return 
    ; 
  } 
   
  Viewgroup.layoutparams params = Mcontainer.getlayoutparams (); 
  if (null!= params) { 
    if (show) { 
      params.height = ViewGroup.LayoutParams.WRAP_CONTENT; 
    } else { 
      params.height = 0; 
    } 
     
    Requestlayout (); 
    Setvisibility (show?) View.VISIBLE:View.INVISIBLE); 
  } 
 

After you change the Layoutparameter, call the Requestlayout () method.

Picture rotation compatible 2.x system

I was thinking before this only need to be compatible with more than 3.x of the system, but found that a lot of users in the use of the process encountered compatibility problems, this time will be the compatibility of this implementation.

Onpull's modifications are as follows:

  @Override public 
void Onpull (float scale) { 
  if (null = = Mrotationhelper) { 
    mrotationhelper = new Imageviewrot Ationhelper (Marrowimageview); 
  } 
   
  float angle = scale * 180F; Suppress Checkstyle 
  mrotationhelper.setrotation (angle); 
} 

Imageviewrotationhelper The main role is to achieve the ImageView rotation function, the internal version of the distinction, the implementation code is as follows:

/** * The image View Rotation helper * * @author lihong06 * @since 2014-5-2/Static Class Imagev 
    Iewrotationhelper {/** the ImageView * * Private final ImageView Mimageview; 
    /** The Matrix * * Private matrix Mmatrix; 
    /** Pivot X * * Private float mrotationpivotx; 
     
    /** Pivot Y * * Private float Mrotationpivoty; 
     /** * The constructor method. * * @param imageview the image View */public Imageviewrotationhelper (ImageView imageview) {Mimag 
    Eview = ImageView; }/** * Sets the degrees that's the view is rotated around the pivot point. 
     Increasing values * result in clockwise rotation. 
     * * @param rotation the degrees of rotation. 
     * * @see #getRotation () * @see #getPivotX () * @see #getPivotY () * @see #setRotationX (float) * @see #setRotationY (float) * * @attr ref Android. R.styleable#view_rotation * 
    public void setrotation (float rotation) {if (Apiutils.hashoneycomb ()) {mimageview.setrotation (rota 
      tion); 
           
          else {if (null = = Mmatrix) {Mmatrix = new Matrix (); 
          Compute the center point of the rotation drawable imagedrawable = mimageview.getdrawable (); 
            if (null!= imagedrawable) {mrotationpivotx = Math.Round (Imagedrawable.getintrinsicwidth ()/2f); 
          Mrotationpivoty = Math.Round (Imagedrawable.getintrinsicheight ()/2f); 
        } mmatrix.setrotate (Rotation, mrotationpivotx, mrotationpivoty); 
      Mimageview.setimagematrix (Mmatrix); 

 } 
    } 
  }

The core of this is that if you are on a 2.x version, rotate the imageview using the matrix.

The Pulltorefreshbase construction method is compatible with 2.x

The constructor method for three parameters declares the following annotation:

@SuppressLint ("Newapi")

@TargetApi (build.version_codes. Honeycomb)

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.