Android Development Diffutils Create a different Recyclerview

Source: Internet
Author: User
Tags call back

Briefly

Diffutil is a new class from the Recyclerview support Library V7 24.2.0, according to Google's official documentation, the role of Diffutil is to compare two data lists and to calculate a series of actions to convert old data tables into new ones. This concept is abstract, in another way, Diffutil is a tool class that, when your recyclerview needs to update data, passes the old and new datasets to it, it can quickly tell adapter what data needs to be updated. It is equivalent to a change on an item refresh, no change will not be refreshed, can be referred to as local refresh.

No brain refresh vs local Refresh

First we need to know that Diffutil uses the difference algorithm of Eugene W Myers to calculate the minimum amount of update to convert one dataset to another, that is, to convert one dataset to another in the simplest way. Diffutil can also identify the movement of a data in a data set. However, the algorithm does not detect mobile items, so Google improves support for detecting mobile projects based on it, but detecting mobile items can be more performance-intensive. The following is the length of the operation on the Nexus 5X system given by Google's website:

    • 100 data, 10 changes: Average 0.39ms, median: 0.35ms.
    • 100 data, 100 changes:
      • When shift recognition is turned on: average: 3.82ms, median: 3.75ms.
      • When shift recognition is off: average: 2.09ms, median: 2.06ms.
    • 1000 data, 50 changes:
      • When shift recognition is turned on: average: 4.67ms, median: 4.59ms.
      • When shift recognition is off: average: 3.59ms, median: 3.50ms.
    • 1000 data, 200 changes:
      • When shift recognition is turned on: average: 27.07ms, median: 26.92ms.
      • When shift recognition is off: average: 13.54ms, median: 13.36ms.
Use Posture

First, we have to learn how to use it, and second, we need to know what posture to use it, posture is not right, all in vain.

Diffutils.callback

Let's take a look at the source code of Diffutils callback:

/** * A CallbackclassUsed byDiffutil whileCalculating theDiffbetweenThe lists. * When using diffutils, this is a calculation2AListDifferent callback functions */public abstract staticclassCallback {/** * Returns theSize of  theOldList.        * Get old data source size */public abstract int getoldlistsize (); /** * Returns theSize of  theNewList.        * Get new Data source size */public abstract int getnewlistsize (); /** * called by  theDiffutil toDecide whether object represent theSame Item. * For example,ifYour items has a unique IDs, this method should check theirIDEquality.         * <p> * is called by Diffutil to determine if two objects are the same item. * For example, if your item has a uniqueIDfield, this method will judgeIDare equal. * @param olditemposition the position of  the Item inch  theOldList* The old dataItem* @param newitemposition the position of  the Item inch  theNewList* The new dataItem* @returnTrueif  theBoth items represent theSame objector false ifThey is different. *trueRepresents the2AItemSame content, otherwise, different */public abstractBooleanAreitemsthesame (int olditemposition, int newitemposition); /** * called by  theDiffutil whenitWants toCheck whether the other items have theSame data. * Diffutil uses this information toDetectif  the Contents  ofAnItemHas changed. * Diffutil uses this method toCheck equalityinstead of{@link Object#equals (Object)}* SO thatYou can change itsBehavior depending onYour UI. * For example,ifYou is using Diffutil withA * {@link android.support.v7.widget.RecyclerView.Adapter recyclerview.adapter}, you should *returnWhether theItems ' visual representations is theSame. * This method isCalled onlyif{@link#areItemsTheSame (int, int)} returns* {@codetrue} forThese items. * Called by Diffutil to check for twoItemWhether it contains the same data * Diffutil with the returned information (true/false) to detect the currentItemWhether the content has changed * so you can change its return value according to your UI * Diffutil this method insteadequalsmethod to check for equality.         * For example, if you use Recyclerview.adapter with Diffutil, you need to return the item to see if the visual representation is the same. * This method only returns in Areitemsthesame ()trueCalled only when the. * @param olditemposition the position of  the Item inch  theOldList* The old dataItem* @param newitemposition the position of  the Item inch  theNewListwhich replaces the* Olditem * New data Some replace the old dataItem* @returnTrueif  the Contents  of  theItems are theSameor false ifThey is different. *trueRepresents the2AItemSame content, otherwise, different */public abstractBooleanArecontentsthesame (int olditemposition, int newitemposition); /** * When {@link#areItemsTheSame (int, int)} returns {@code true} for both items and* {@link#areContentsTheSame (int, int)} returns false for them, Diffutil* calls this method to GetA payload About  theChange. * <p> * For example,ifYou is using Diffutil with{@link Recyclerview}, you canreturn  the* Particular field thatChangedinch  the Item  andYour * {@link android.support.v7.widget.RecyclerView.ItemAnimator itemanimator} can use that* Information to Run  theCorrect animation.         * <p> * Default implementation returns {@code null}. * * when areitemsthesame (int, int) returnstrue, and arecontentsthesame (int, int) returnsfalse, Diffutils will call back to this method, * to get the payload of this item (there are some) changes. * For example, if you are using Recyclerview with Diffutils, you can return to the fields that the item changed, and you can use that information to perform the correct animation * The default implementation is to return NULL * @param olditemposit Ion the position of  the Item inch  theOldList* postion in old data sources * @param newitemposition the position of  the Item inch  theNewList* Position in New data source * @returnA Payload Object thatRepresents theChangebetween  theBoth items. * Return a representative of the new and oldItemThe payload object that changes the content, */@Nullable public object Getchangepayload (int olditemposition, int newitempositi ON) {returnNull }    }

Above is a description of the whole callback, I have annotated Chinese, you can understand the next, we are looking at.

Use in correct posture

I have briefly introduced callback's annotations. Now we can achieve our own through inheritance.

 Public  class swdiffcallback extends diffutil. Callback {    PrivateList<string> Olddatas;PrivateList<string> Newdatas; Public Swdiffcallback(list<string> Olddatas, list<string> Newdatas) { This. Olddatas = Olddatas; This. Newdatas = Newdatas; } Public int getoldlistsize() {returnOlddatas.size (); } Public int getnewlistsize() {returnNewdatas.size (); } Public Boolean Areitemsthesame(intOlditemposition,intNewitemposition) {returnOlddatas.get (olditemposition). Equals (Newdatas.get (newitemposition)); } Public Boolean Arecontentsthesame(intOlditemposition,intNewitemposition) {returnOlddatas.get (olditemposition). Equals (Newdatas.get (newitemposition)); }}

Simple custom Callback We've implemented it, let's see how it's used.

NewList =NewArraylist<> (); for(inti =1; I <List. Size (); i++) {Newlist.add (List. get (i) +""); } newlist.add (5,List. Size () + j +""); j + +;//Normal refresh                //list=newlist;//Adapter.setlist (newlist);//Adapter.notifydatasetchanged ();                //strong local RefreshDiffutil.diffresult Diffresult = Diffutil.calculatediff (NewSwdiffcallback (List, NewList),true);//Use the Dispatchupdatesto () method of the Diffutil.diffresult object to pass in the adapter of the Recyclerview                //Don't forget to give the new data to adapter                List= NewList; Adapter.setlist (List); Diffresult.dispatchupdatesto (adapter);

Looks much better than the global refresh code? It doesn't matter, let's take a look at what it says.

A wave of 666, as well as a self-brought animation. We're looking at a normal global refresh.

It looks a lot simpler than diffutils, but when you're really on the web requesting it, you'll find it's completely different, and the whole screen will flash-yes, just a flash. Before the test let me change this bug, I am a bit too, can't change AH--unless rewritten. So, Diffutils is still very powerful, the demo will be released at the end of the text, you can download their own run to see.

Posture Advanced Use

We looked before the use, is not found, I resolved callback, and I wrote the demo, a less method, yes, is getchangepayload. What does this do? It's my whole list. Only one item of data changes, I just need to replace that one data without needing to replace the whole item.
OK, let's just write a demo of the test. The code is simple:

 Public  class swloaddiffcallback extends swdiffcallback{//Private list<bean> oldlist;//Private list<bean> newlist;     Public Swloaddiffcallback(list<string> Olddatas, list<string> Newdatas) {Super(Olddatas, Newdatas); } PublicObjectGetchangepayload(intOlditemposition,intNewitemposition) {//Bean Olditem = Oldlist.get (olditemposition);//Bean NewItem = Newlist.get (newitemposition);//Bundle Diffbundle = new bundle ();//if (!newitem.header.equals (Olditem.header)) {//Diffbundle.putstring (Key_heeder, newitem.header);//        }//if (!newitem.footer.equals (Olditem.footer)) {//Diffbundle.putstring (Key_footer, newitem.footer);//        }//if (diffbundle.size () = = 0)            return NULL;//return diffbundle;}

This we write a bean, inside we put the header and footer, and then make a comparison, this way I will not write the demo. Believe in this writing you should be able to read. Code I have uploaded to csdn: Click to download Demo

Summarize

1.Diffutils is very suitable for various refresh operations, I have integrated him into my open source, you can see for yourself.
The 2.Diffutils implementation of the local refresh contains his own animation effect, so we do not have to deal with, and looks more beautiful ~
3.DiffUtil can be used for efficient recyclerview data updates, but the Diffutil itself is designed to calculate the minimum update for a dataset. Diffutil has powerful algorithm support, and can use Diffutil to accomplish many other functions.

Android Development Diffutils Create a different Recyclerview

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.