Android application series: ViewHolder tool class implementation worth collecting

Android application series: ViewHolder tool class implementation worth collecting

Preface

In the process of developing APP, engineers have to flirt with components such as ListView and GridView. The natural and original beauty BaseAdapter is the favorite of programmers. With it, we can do whatever we want. Hehe, you know haha~

However, every time we write a BaseAdapter, we consciously write a ViewHolder for it. One or two is fine, but what if there are countless ListViews in the application? Hehe~ Damn! The same old things are boring. As the greatest programmers of the 22nd century, taking off and putting on are always our most sincere pursuits, so how do we take ViewHolder off from BaseAdapter? It is not that we don't use it, but that we should make it into a gorgeous tool class implementation and put it into the lonely tools class in the corner.

ViewHolder Implementation

I think I should briefly introduce the implementation of ViewHolder. Google cleverly used the idea of ​​reusing View in Adapter, which naturally makes it possible for our loser phones to pick up some beautiful and rich girls. The specific implementation of ViewHolder is basically reflected in the getView(int position, View convertView, ViewGroup parent) method of BaseAdapter, see the following code:

  1. @Override  
  2. public View getView( int position, View convertView, ViewGroup parent) {
  3. ViewHolder holder;
  4. if (convertView == null ) {
  5. convertView = inflater.inflate(R.layout.listview_item_layout, parent, false );
  6. holder = new ViewHolder();
  7. holder.studentName = (TextView) convertView.findViewById(R.id.student_name);
  8. holder.studentAge = (TextView) convertView.findViewById(R.id.student_age);
  9. convertView.setTag(holder);
  10. }
  11. else {
  12. holder = (ViewHolder) convertView.getTag();
  13. }
  14. Student data = (Student) getItem(position);
  15. holder.studentName.setText(data.getName());
  16. holder.studentAge.setText(data.getAge());
  17. return convertView;
  18. }
  19.  
  20. class ViewHolder {
  21. public TextView studentName;
  22. public TextView studentAge;
  23. }

Obviously, don't ask me where ViewHolder is. Just look up and you will see the big class ViewHolder. ViewHolder is used in two places. One is the reuse of convertView, and the other is the reuse of indexes in ViewHolder, which is convertView. If you are not familiar with the specific usage, you can search Baidu. If I go on, I will be sorry for my blog post today, because the purpose of writing this code here is definitely not to introduce how to use ViewHolder. I just want to tell you: how bloated the traditional ViewHolder is! And for each new BaseAdapter, you have to implement it again and again, OH~

ViewHolder tool class implementation

Of course, we should start stripping when we are young and take action as early as possible. Since we are tired of it, let's write it into a tool class. See the code below

  1. static   class ViewHolder {
  2. public   static <T extends View> T get(View view, int id) {
  3. SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
  4. if (viewHolder == null ) {
  5. viewHolder = new SparseArray<View>();
  6. view.setTag(viewHolder);
  7. }
  8. View childView = viewHolder.get(id);
  9. if (childView == null ) {
  10. childView = view.findViewById(id);
  11. viewHolder.put(id, childView);
  12. }
  13. return (T) childView;
  14. }
  15. }

This is the implementation of the tool class. Let me briefly explain the principle of implementation:

1. Since ViewHolder depends on the View's Tag storage, it is stored in a SparseArray collection.

2. Determine whether the Tag in the View exists in a viewHolder. If not, ask her to give birth to one immediately.

3. Then find the index of View in viewholder (that is, SparseArray). If it is not there, quickly findViewById and put it in and return it. If it already exists, everyone is happy and use it directly.

Paste the code used in BaseAdapter:

  1. @Override  
  2. public View getView( int position, View convertView, ViewGroup parent) {
  3. if (convertView == null ) {
  4. convertView = inflater.inflate(R.layout.listview_item_layout, parent, false );
  5. }
  6. TextView name = Tools.ViewHolder.get(convertView, R.id.student_name);
  7. TextView age = Tools.ViewHolder.get(convertView, R.id.student_age);
  8.      
  9. Student data = (Student) getItem(position);
  10. name.setText(data.getName());
  11. age.setText(data.getAge());
  12.      
  13. return convertView;
  14. }

It's concise and clear, no need to say more~~~ Hehe, if you want to write ViewHolder later, just call the Tools tool class directly, which saves you trouble and brain. .

Analyze feasibility

Since it is to be used as a tool, we need to first evaluate whether this tool is worth using.

Generally speaking, we can evaluate from the following aspects: ease of use? Memory leaks? Performance improvement? Robustness? And so on. . . . .

Ease of use: The biggest feature of the tool class is its simplicity and ease of use. The writing of this ViewHolder is a typical use-it-now approach. We don’t have to worry about writing some adaptation code at all. We can directly pass in the View and id, which is highly cohesive and loosely coupled. And it uses the generic template method of <T extends View> T to automatically adapt to the external View subclass, without us having to manually force the conversion.

Memory leak: Some beginners will stubbornly believe that the SparseArray<View> viewHolder variable will have memory leaks when seeing static methods, but Java tells us that the life of this variable is only during the execution of the method. When the method is completed, it will be recycled by GC; the ViewHolder is placed in the Tag of the View as always. Once the View is recycled, the ViewHolder will disappear naturally. If you don't believe it, open DDMS and try to refresh the listView with your 28-year-old hand speed to ensure that the object is basically stable at a value.

Performance improvement: Here we find that the SparseArray collection is used instead of HashMap. We know that SparseArray is a tool class of Android and is officially recommended to replace HashMap<Integer,E>. It uses binary search internally to improve search efficiency. And it is not just a little bit. Anyone who uses it knows it. If you want to know the specific content, you can go to Baidu Google or Zuozhuan source code.

Therefore, as a tool class, it is fully qualified. Hurry up and copy it to your tools or utils, and then we can use ViewHolder happily and elegantly.

<<:  Some technologies of Visual Studio Code come from Github

>>:  Selling one app in two parts, this is Google's new strategy

Recommend

Arrow points to manned lunar landing! Long March 10 is on schedule

The manned space station project has fully entere...

Getting Started with SEO, How Do Newbies Learn SEO?

SEO website optimization, this technology has a h...

"Let's sing karaoke!": Why do we sing out of tune?

The protagonist of the movie "Let's Go K...

Sleeping less than 6 hours a day may even lead to crime?!

Source: Higher-end humans This article has been a...

Walk more, be healthier, life lies in strolling...the same goes for birds!

The chicks of the Grey-headed Lapwing are precoci...

Review of Double 11 marketing cases in 2018! Recommended for collection!

It’s Double 11 again this year, and the carnival ...

4 Steps to Reconstruct Growth Hacking Logic

Even the new graduates I teach know the AARRR mod...

APP new user promotion丨How to attract traffic to APP through H5 activities?

When operating an APP, it is bound to involve the...

How does the popular "dopamine outfit" heal your and my mood?

The new favorite in the fashion circle that has b...

Pollen and catkins season, these drugs are more life-saving than loratadine

【Appendix】Tips for using loratadine 1. Although l...

The third AIDS patient was "cured"! Can humans finally conquer AIDS?

On February 15, American researchers reported the...