Android Development Learning Path-diffutil Use tutorial

Source: Internet
Author: User

Google has recently updated support Library 24.2.0, and Diffutil is a tool class added in this release.

Diffutil is a tool class for finding sets of changes, and is used with Recyclerview, if you don't know Recyclerview, you can read some materials or my blog: recyclerview use

According to convention, first put:

As you can see, when we click on the button, the set of the Recyclerview is changed and some elements are added (8). Jason), and some elements have been moved (3. Rose), was even modified (2. fndroid). Recyclerview animations for each item are refreshed in a different way:

    • notifyiteminserted
    • Notifyitemchanged
    • Notifyitemmoved
    • Notifyitemremoved

For a continuous refresh of several item, you can call:

    • Notifyitemrangechanged
    • notifyitemrangeinserted
    • Notifyitemrangeremoved

As the collection changes, only the Notifydatasetchanged method can be called to refresh the entire interface, and it is not possible to animate each changed element according to the change of the collection. So here's a diffutil to solve the problem.

The function of Diffutil is to find out the changes in each item in the collection and then give each change a corresponding refresh.

This diffutil uses the Eugene Myers algorithm, the algorithm itself can not check the movement of elements, that is, the movement can only be counted as deleted, then increase, and diffutil is the result of the algorithm after a move check. It is assumed that the time complexity of the algorithm is O (N + D2) without detection of element movement, while the detection element movement is O (N2). Therefore, if the set itself is already sequenced, it is possible to improve efficiency without moving the detection.

Let's take a look at how this tool is used.

First for each item, the data is a student object:

1 classStudent {2     PrivateString name;3     Private intnum;4 5      PublicStudent (String name,intnum) {6          This. Name =name;7          This. num =num;8     }9 Ten      PublicString GetName () { One         returnname; A     } -  -      Public voidsetName (String name) { the          This. Name =name; -     } -  -      Public intGetnum () { +         returnnum; -     } +  A      Public voidSetnum (intnum) { at          This. num =num; -     } -}

We then define the layout (omitted) and the adapter:

1     classMyadapterextendsRecyclerview.adapter {2         PrivateArraylist<student>data;3 4Arraylist<student>GetData () {5             returndata;6         }7 8         voidSetData (arraylist<student>data) {9              This. data =NewArraylist<>(data);Ten         } One  A @Override -          PublicRecyclerview.viewholder Oncreateviewholder (viewgroup parent,intViewType) { -View Itemview = Layoutinflater.from (recyclerviewactivity. This). Inflate (R.layout.itemview,NULL); the             return NewMyviewholder (itemview); -         } -  - @Override +          Public voidOnbindviewholder (Recyclerview.viewholder holder,intposition) { -Myviewholder Myviewholder =(myviewholder) holder; +Student Student =Data.get (position); AMyViewHolder.tv.setText (Student.getnum () + "." +student.getname ()); at         } -  - @Override -          Public intGetItemCount () { -             returndata.size (); -         } in  -         classMyviewholderextendsRecyclerview.viewholder { to TextView TV; +  - Myviewholder (View itemview) { the                 Super(Itemview); *TV =(TextView) Itemview.findviewbyid (R.ID.ITEM_TV); $             }Panax Notoginseng         } -}

Initialize the data collection:

1     Private voidInitData () {2Students =NewArraylist<>();3Student S1 =NewStudent ("John", 1);4Student s2 =NewStudent ("Curry", 2);5Student s3 =NewStudent ("Rose", 3);6Student S4 =NewStudent ("Dante", 4);7Student S5 =NewStudent ("Lunar", 5);8 Students.add (S1);9 students.add (S2);Ten Students.add (S3); One Students.add (S4); A Students.add (S5); -}

Then instantiate the adapter and set it to Recyclerview:

    @Override    protectedvoid  onCreate (Bundle savedinstancestate) {         Super . OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_recycler_view);        InitData ();         = (Recyclerview) Findviewbyid (R.ID.RV);        Recyclerview.setlayoutmanager (new Linearlayoutmanager (this));         New Myadapter ();        Adapter.setdata (students);        Recyclerview.setadapter (adapter);    }

None of this is the content of this article, but one place to note is the definition of adapter:

1     classMyadapterextendsRecyclerview.adapter {2         PrivateArraylist<student>data;3 4Arraylist<student>GetData () {5             returndata;6         }7 8         voidSetData (arraylist<student>data) {9              This. data =NewArraylist<>(data);Ten         } One  A         //omit part of the code -          ......   -}

The SetData method here is not to save the ArrayList reference directly, but to re-establish a ArrayList, first remember, and later explain why .

How to use Diffutil:

When the mouse is pressed, modify the contents of the ArrayList:

1      Public voidChange (view view) {2Students.set (1,NewStudent ("Fndroid", 2));3Students.add (NewStudent ("Jason", 8));4Student s2 = students.get (2);5Students.remove (2);6 students.add (S2);7 8Arraylist<student> old_students =Adapter.getdata ();9Diffutil.diffresult result = Diffutil.calculatediff (NewMycallback (old_students, students),true);Ten Adapter.setdata (students); One Result.dispatchupdatesto (adapter); A}

The 2-6 row is a modification to the collection, and the 8th row first gets the old data into the collection in adapter.

Focus on the 9th line call Diffutil.calculatediff method to calculate the difference of the collection, here to pass in a callback interface implementation class (for specifying the calculation of the rules) and the old and new data are passed to the interface implementation class, and finally a Boolean parameter, this parameter specifies whether the need to To perform a move detection, if it is not required, if there is an item moved, it is considered to be remove first and then insert. This is specified as true, so there is a moving effect of the motion diagram display.

Line 10th re-sets the new data to adapter.

Line 11th calls the 9th line to get the Dispatchupdatesto method of the Diffresult object to notify Recyclerview to refresh the corresponding item that has changed.

Here goes back to the SetData method described above, because we are here to distinguish two sets, if the SetData method to save the reference directly, then in the 2-6 row of the modification will directly modify the adapter in the collection (Java knowledge).

If the setting does not check the movement of item, the effect is as follows:

Then let's see how the implementation class for the callback interface is defined:

1     Private classMycallbackextendsDiffutil.callback {2         PrivateArraylist<student>old_students, new_students;3 4Mycallback (arraylist<student> data, arraylist<student>students) {5              This. old_students =data;6              This. new_students =students;7         }8 9 @OverrideTen          Public intgetoldlistsize () { One             returnold_students.size (); A         } -  - @Override the          Public intgetnewlistsize () { -             returnnew_students.size (); -         } -  +         //determine if item already exists - @Override +          Public BooleanAreitemsthesame (intOlditemposition,intnewitemposition) { A             returnOld_students.get (olditemposition). Getnum () = =New_students.get (newitemposition). Getnum (); at         } -  -         //If item already exists, this method is called to determine whether the content of item is consistent - @Override -          Public BooleanArecontentsthesame (intOlditemposition,intnewitemposition) { -             returnOld_students.get (olditemposition). GetName (). Equals (New_students.get (newitemposition). GetName ()); in         } -}

Here according to the school number to determine whether the same item, according to the name to determine whether the item has been modified.

Note here: If the recyclerview load a lot of data, then the algorithm may not be completed immediately, pay attention to the problem of ANR, you can open a separate thread to calculate.

Android Development Learning Path-diffutil Use tutorial

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.