Customized implementation of baseadapter for Android (general adapter I)

After optimizing the layout, let's talk about how to create a general adapter. Can a general adapter do? It's very simple. Reduce our writing of the code. Let's start with the code.

MyAdapter. java

In the above code, let's see which code formats or forms are used repeatedly. First, it's not difficult to see whether the three methods of public int getcount(), public long getitemid (int position) and public long getitemid (int position) should be implemented every time. Therefore, we can extract these codes and put them into mybaseadapter, Since the important part of each time is to implement the getview method, we don't need to write this method here. We can directly set mybaseadapter as an abstract class, but we need the class implementing getview to inherit it. Therefore, myadapter can inherit mybaseadapter and then implement the getview method

MyBaseAdapter. java

MyAdapter. java

In this way, each customization only needs to inherit mybaseadapter. However, in that sentence, there is no optimization, only better, so we have to optimize and package. Then, from the above getview method, what other codes are often reused? In fact, you will find that we need to operate the same code every time:

We can understand this code again. First, we need to create a holder object every time and set it to the settag of the corresponding convertview. Then, we need to get the Hoder object every time and operate the controls in the Hoder object. For the above code, we can directly simplify it into the following steps

1. Viewholder = get the holder / / get the corresponding holder object each time. 2 TextView tv = holder. Getview() / / get the ID corresponding to each control 3 tv. Settext() / / operate the control 4 Return view / / return to view

Let's start writing a general viewholder class to optimize our implementation. The code is as follows:

ViewHolder. java

Through the above code, we have encapsulated a general viewholder class. Here is our myadapter Java can simply write the following code:

Well, the above code is not simpler. In fact, we only encapsulate the viewholder class here. There are more general ones waiting for us to encapsulate. Next time, what we need to encapsulate is how to encapsulate the code in getview again, which has achieved better performance.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>