Android Recyclerview Data Binding Instance code _android

Source: Internet
Author: User
Tags event listener

Objective

In the last project there are a lot of many a lot of recyclerview, and then I need to write a lot of many many a lot of adapter and viewholder--is no problem, but there are a lot of duplicate code that can not endure! Every adapter and Viewholder actually do something very much like: view binding, data binding, click event Distribution. What else is there? Since they are doing the same thing, why do we still have to be silly to continue to write repetitive code?

Body

Baseadapter

Usually we want to create a recyclerview.adapter how to do it?

    1. Receive a list of data
    2. Rewrite the GetItemCount () method to determine the number of items
    3. Rewrite the Oncreateviewholder () method, bind layout, and create a new one that we wrote ourselves Recyclerview.viewholder
    4. Overriding the Onbindviewholder () method for data and view binding
    5. Since Recyclerview did not write click events, the Click event was distributed

Basically this is the routine, or add a RefreshData () method--Pass the new data in and then Notifydatasetchanged (). Based on these points, I wrote a baseadapter base class:


/** * Adapter base class.
 * Applies to Recyclerview with only a single item.
 * * Created by Lypeer on 16-5-24. * * Public abstract class Baseadapter<v> extends Recyclerview.adapter<recyclerview.viewholder> {/** * loaded every

 List of the value of the item * * Private list<v> mvaluelist;

 /** * I write an interface through the callback distribution click event/private onitemclicklistener<v> Monitemclicklistener; @Override public Recyclerview.viewholder Oncreateviewholder (viewgroup parent, int viewtype) {return Createviewholder (p
 Arent.getcontext (), parent); @Override @SuppressWarnings ("unchecked")//Must be a subclass of Baseviewholder because the return value of Createviewholder () is public void Onbindviewholder (recyclerview.viewholder holder, int position) {// Baseviewholder is the base class of the Recyclerview.viewholder I abstracted, which is explained in detail below (baseviewholder) holder. SetData (
 position), position, Monitemclicklistener); /** * Set the Click event for each item * @param listener/public void Setonclicklistener (Onitemclicklistener<v> listener) {This.monitemclicklistener = ListenEr /** * Refresh Data * @param valuelist new Data list * * public void RefreshData (list<v> valuelist) {this.mvaluelist =
  ValueList;
 Notifydatasetchanged ();
 @Override public int GetItemCount () {return mvaluelist = = null 0:mvaluelist.size (); /** * Generate Viewholder * @param context * @param parent * @return/protected abstract Baseviewholder Createvi
Ewholder (context, viewgroup parent);

 }

Its subclasses need to specify the specific type of generic when inheriting it, because different item may be the same data type, so that it can accommodate more item. In addition, an interface Onitemclicklistener is mentioned, and this interface is simple:

/**
 * Click event interface
 * Created by Lypeer on 16-5-24.
 * * Public
interface onitemclicklistener<v> {

 /**
  * When item is clicked to distribute the event
  *
  * @param itemvalue Click on the item pass value
  * @param viewid Click the control's ID
  * @param position the location of the item being clicked
 /void Onitemclick (V itemvalue, int viewid, int position);
}

You also need to use generics when using it-for the same reason as above.

With the above baseadapter, we encapsulate a lot of common operations in the base class, and its subclasses just need to create a different viewholder on demand--and, of course, this viewholder must inherit from Baseviewholder, And Baseviewholder is what the following will be explained in detail. Next is an example, assuming that we now have a recyclerview in an interface where the data for each item is a string value, how do we use our baseadapter to simplify the development process?

public class Sampleadapter extends baseadapter<string> {
 @Override
 protected Baseviewholder Createviewholder (Context context, ViewGroup parent) {
  //sampleviewholder inherits from Baseviewholder return
  new Sampleviewholder (context, parent);
 }

Yes, you're not mistaken! There are only a few lines of code! 5 Seconds to complete! Surprise?!

You just need to create a new sampleadapter to inherit from Baseadapter, then specify its generic string, then return to new Sampleviewholder (context, parent) and complete the operation.

But some readers may wonder: maybe we need to do a lot of sampleviewholder inside? Isn't it just a place where the code has been converted, and there's really no optimization at all?

But it's not.

Baseviewholder

I always thought it would be unwise to write Viewholder in adapter. In this case, the responsibility of this class is too heavy, it is doing too much, from the data received to the interface binding, from the control initialization to click event Distribution, it is almost done adapter. And this is very bad. Very easily, a more complex Recyclerview adapter code can reach hundreds and thousands of rows, which is frightening, meaning that this class will become jumbled and difficult to maintain. So how do you avoid this happening? I chose to separate the Viewholder, while aggravating the duties of viewholder to make them more balanced.

Look directly at the Baseviewholder code:

/** * Viewholder base class * * Created by Lypeer on 16-5-27. */Public abstract class Baseviewholder<v> extends Recyclerview.viewholder {public Baseviewholder
  , viewgroup root, int layoutres) {Super (Layoutinflater.from (context). inflate (Layoutres, root, false));
 The butterknife is used to bind the control Butterknife.bind (this, itemview);
  /** * facilitates its subclasses to perform some operations that require context.
 * * @return The context of the caller * * * GetContext () {return itemview.getcontext ();
  /** * Abstract method, binding data.
 * Allow subclasses to bind data and view themselves * * @param itemvalue Item data * @param position the current item position * @param Listener Click event Listener * *

 protected abstract void Binddata (V itemvalue, int position, Onitemclicklistener listener); /** * used to transmit data and information * * @param itemvalue * @param position * @param listener/public void SetData (V itemvalue,
 int position, Onitemclicklistener listener) {Binddata (itemvalue, position, listener); }
}

Baseviewholder also uses generics to accommodate different data types. At the same time, I used the baseviewholder inside the Butterknife to simplify the code, no longer need to repeatedly findviewbyid.

In addition, you can see the baseviewholder inside the construction method passed three parameters, but in the above Baseadapter example Sampleviewholder construction method we have only passed its first two tectonic parameters, and the third parameter layoutres did not pass in, this is how to go about? Is it written wrong? Of course not. The Baseviewholder construct method has three arguments because it requires three arguments, and its subclass has only two arguments because it can have only two arguments. _baseviewholder must satisfy its super structure, so must have the three parameters, and its subclass if the three parameters are passed in by the outside, then how does it for the layout of the special alienation of operation? it must be explicitly specified within the class layout id_--This is actually I would like to optimize a place, because of such words after the subclass inherits Baseviewholder also want to modify its construction method, this is more people not worry, But there is no good idea yet to optimize it gracefully.

There are two ways in Baseviewholder that look alike: SetData () and Binddata (), but in fact, except for the same parameters, they are completely different in other ways. The SetData () method is a public method that can be invoked by an object of a Baseviewholder subclass, and its function is to pass data from the outside to initialize the view that Viewholder hold, which can be said to be a bridge for transmitting information. While GetData () is an abstract method, its concrete implementation in each Baseviewholder subclass, these subclasses in this method to control the binding and initialization, as well as the control of the Click event processing and so on.

When it comes to the handling of click events, how does its subclasses accomplish this? Through the Onitemclicklistener. We can use the Onitemclicklistener interface callback to transfer the Click events that need to be handled to the outside world and then to be processed by the outside world. So what if the click event of multiple controls needs to be handled? Don't worry, because in the Onitemclicklistener onclick method you need to pass in the ID of the control you clicked on, so that you can judge the incoming ID from the outside, and then perform a different click event for different IDs.

Next, let's take a look at the specific how to use, is the top of the Sampleviewholder bar:

 public class Sampleviewholder extends baseviewholder<string> {//an ordinary clickable TEXTVI

 EW @Bind (r.id.is_tv_content) TextView mistvcontent; Public Sampleviewholder (context context, ViewGroup root) {//Modify the constructor method, where you explicitly specify Layout ID super (context, root, r.layout.it
 Em_sample);
  @Override protected void Binddata (final String itemvalue, final int position, Final Onitemclicklistener listener) {
  This completes the initialization of the control and binds it to the data binding if (Itemvalue!= null) {Mistvcontent.settext (itemvalue); //If you need to have a click event, pass it through listener Mistvcontent.setonclicklistener (new View.onclicklistener () {@Override public vo ID OnClick (View v) {//If the outside world does not call Baseadapter.setonclicklistener (),//listener is null if (listener = null) {R
    Eturn;
   //listener this event to external processing Listener.onitemclick (Itemvalue, V.getid (), position) without being null;
 }
  }); }
}

It is also very simple, convenient and quick and clear. But there are a few noteworthy points to note. First of all, you can not forget to modify the construction method, explicit in the super inside the designation layout ID, or the next step can not do, then the Meng. In addition, the Listener.onclick () method must be listener when it is called--because listener is really possible to be empty! This makes it very easy to produce an empty exception that causes the program to crash.

Bingo, so the Sampleviewholder is done, and almost effortlessly.

Conclusion

The purpose of this blog post is to share some of the things I've summed up, hoping to accelerate the development of everyone. Of course, this may also have I did not find a bug or something, if you have found a problem in the use of the process, please do not be polite, mercilessly hit me!

Finally, and then summed up in the case of Baseadapter and baseviewholder the fastest way to get the Recyclerview of the set:

Viewholder related
The new Xxxviewholder inherits from Baseviewholder, specifying the generic type (that is, the data type of the data in item).
Delete the Layoutres parameter in the constructor method and explicitly specify the layout ID in Super.
Bind the control with Butterknife.
Complete the initialization of the control and the passing of the Click event in the Binddata () method (don't forget the listener)

Adapter related

The new xxxadapter inherits from Baseadapter, specifying the generic type (that is, the data type of the data in item).
Return to new Xxxviewholder (context, parent);

External related

Bind Recyclerview, New Xxxadapter.
Call the Baseadapter.refreshdata () method to pass in the list of data.
Call the Baseadapter.setonclicklistener () method if there is a demand for the Click event Processing.

At the moment I've only done the baseadapter for a single item in Recyclerview, but Baseviewholder makes it universal, and it can greatly simplify adapter volume under multiple item.

The above is to the Android Recyclerview data binding information collation, follow-up to continue to supplement the relevant information thank you for your support of this site!

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.