Generic Adapter for components such as ListView and GridView in Android

Source: Internet
Author: User

Generic Adapter for components such as ListView and GridView in Android

Today, I casually walked around CSDN and saw an article on the home page recommending the Android quick development series to create a omnipotent ListView GridView adapter. Just in the past two days, I wrote a project and encapsulated a similar CommonAdapter, I have seen such a library on github before, so I also sorted out my code and shared it with you. I also hope that I can learn more on the CSDN platform, let's take a look.

Adapter is usually used in both ListView and GridView components in the project. In many cases, it is inherited from BaseAdapter, and then getCount, getView, and other methods are implemented, use ViewHolder to Improve the efficiency. let's look at the following simple example:

ListView layout File

Fragment_main.xml:

     
  
 
Layout file of the ListView subitem

Listview_item_layout.xml:

 
     
      
  
 

The Adapter code we used to write down
public class NormalAdapter extends BaseAdapter {    Context mContext;    LayoutInflater mInflater;    List
 
   mDataList;    /**     * @param context     * @param data     */    public NormalAdapter(Context context, List
  
    data) {        mContext = context;        mInflater = LayoutInflater.from(context);        mDataList = data;    }    @Override    public int getCount() {        return mDataList.size();    }    @Override    public ListViewItem getItem(int position) {        return mDataList.get(position);    }    @Override    public long getItemId(int position) {        return position;    }    @Override    public View getView(int position, View convertView, ViewGroup parent) {        ViewHolder viewHolder = null;        if (convertView == null) {            convertView = mInflater.inflate(R.layout.listview_item_layout, null, false);            viewHolder = new ViewHolder();            viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.my_imageview);            viewHolder.mTextView = (TextView) convertView.findViewById(R.id.my_textview);            convertView.setTag(viewHolder);        } else {            viewHolder = (ViewHolder) convertView.getTag();        }        viewHolder.mImageView.setImageResource(getItem(position).mDrawableId);        viewHolder.mTextView.setText(getItem(position).mText);        return convertView;    }    /**     * ViewHolder     *      * @author mrsimple     */    static class ViewHolder {        ImageView mImageView;        TextView mTextView;    }}
  
 

However, after writing the code too many times, we find that we are repeatedly writing the getCount, getItem, getView method, and ViewHolder, which leads to a lot of repetitive work and boring, so I abstracted the repetitive work (previously I saw such a general Adapter implementation on github) and sorted it out to make it easy for me to use. It is also a process of self-learning. Next let's take a look at how we need to write the same work as above after using CommonAdapter.

Code to be written after CommonAdapter is used
CommonAdapter
 
  
ListAdapter = new CommonAdapter
  
   
(GetActivity (), R. layout. listview_item_layout, mockListViewItems () {@ Override protected void fillItemData (CommonViewHolder viewHolder, ListViewItem item) {// sets the picture viewHolder. setImageForView (R. id. my_imageview, item. mDrawableId); // set text viewHolder. setTextForTextView (R. id. my_textview, item. mText );}}
  
 

Here, mockListViewImtes prepares some data. The Code is as follows:
/*** Simulate some data ** @ return */private List
 
  
MockListViewItems () {List
  
   
DataItems = new ArrayList
   
    
(); DataItems. add (new ListViewItem (R. drawable. girl_96, "girl_96.png"); dataItems. add (new ListViewItem (R. drawable. fire_96, "fire_96.png"); dataItems. add (new ListViewItem (R. drawable. grimace_96, "grimace_96.png"); dataItems. add (new ListViewItem (R. drawable. laugh_96, "laugh_96.png"); return dataItems ;}
   
  
 

We can see that the amount of code is much reduced. If there are several components such as ListView and GridView in a project, we do not need to repeat so much boring work. Let's take a look:


CommonAdapter implementation

/***** Created by Mr. simple, Aug 28,201 412: 26: 52 PM. * Copyright (c) 2014, hehonghui@umeng.com All Rights Reserved. **###################################### ################ * # _ oo0oo _ # * # o8888888o # * #88 ". "88 # * # (|-_-|) # * #0 \ =/0 #*#___/'---'\___#*#. '\ | #'. # * #/\ |: | # * #/_ | -: -|-\ # * # | \-#/| # * # | \ _ | ''\ ---/'' | _/| # *# \. -\__'-'___/-. /#*#___'.. '/--. --\'.. '___#*#. "" '<'. ___ \_< |> _/___. '> '"". # * # | :'-\'.; '\_/';. '/-': | #*#\\'_. \___\/___/. -'// # * ##==== '-. ____'. ___\_____/___. -'___. -'= ==#* #' = --- = '#*#~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~ ####* # Buddha bless never has a BUG #*##*######################## ########################### */package com. uit. commons; import android. content. context; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import java. util. list;/*** this is a generic and abstract adapter class that overwrites the getCount, getItem, getItemId, * getView method of BaseAdapter, in the getView method, * Common CommonViewHolder is used to process convertView, and other View elements in convertView are cached. * This reduces the amount of code for the Adapter and ViewHolder of components such as ListView and GridView. * You only need to fill the data at the position in the listview or the position view of the gridview in the fillItemData function. * For details about how to use the instance reference documentation, see. ** @ author mrsimple * @ param
 
  
Data Source Type */public abstract class CommonAdapter
  
   
Extends BaseAdapter {/*** Context */Context mContext;/***** List of data to be displayed */List
   
    
MData;/*** the layout id of each item, such as R. layout. my_listview_item. */private int mItemLayoutId =-1;/*** @ param context Context * @ param itemLayoutResId * The layout resource id of each item (applicable to the AbsListView subclass such as listview and gridview, for example, R. layout. * my_listview_item. * @ param dataSource data source */public CommonAdapter (Context context, int itemLayoutResId, List
    
     
DataSource) {checkParams (context, itemLayoutResId, dataSource); mContext = context; mItemLayoutId = itemLayoutResId; mData = dataSource ;} /*** check the parameter validity ** @ param context * @ param itemLayoutResId * @ param dataSource */private void checkParams (Context context, int itemLayoutResId, List
     
      
DataSource) {if (context = null | itemLayoutResId <0 | dataSource = null) {throw new RuntimeException ("context = null | itemLayoutResId <0 | dataSource = null, please check your params ");}} /*** total number of returned data */@ Override public int getCount () {return mData. size ();}/*** return position data */@ Override public T getItem (int position) {return mData. get (position);}/*** item id, return position */@ Override public long getItemId (int position) {return position ;} /*** return the position view, that is, the postion view of listview and gridview */@ Override public View getView (int position, View convertView, ViewGroup parent) {// obtain ViewHolder CommonViewHolder viewHolder = CommonViewHolder. getViewHolder (mContext, convertView, mItemLayoutId); // fill data fillItemData (viewHolder, getItem (position); // return convertview return viewHolder. getConvertView ();}/*** the user must override this method to fill the data in the view. ** @ param viewHolder: ViewHolder, which will load listview, * view of each item of components such as gridview, and cache the position data of its sub-view * @ param item data source */protected abstract void fillItemData (CommonViewHolder viewHolder, T item );}
     
    
   
  
 

CommonViewHolder implementation

/***** Created by Mr. simple, Aug 28,201 412: 32: 45 PM. * Copyright (c) 2014, hehonghui@umeng.com All Rights Reserved. **###################################### ################ * # _ oo0oo _ # * # o8888888o # * #88 ". "88 # * # (|-_-|) # * #0 \ =/0 #*#___/'---'\___#*#. '\ | #'. # * #/\ |: | # * #/_ | -: -|-\ # * # | \-#/| # * # | \ _ | ''\ ---/'' | _/| # *# \. -\__'-'___/-. /#*#___'.. '/--. --\'.. '___#*#. "" '<'. ___ \_< |> _/___. '> '"". # * # | :'-\'.; '\_/';. '/-': | #*#\\'_. \___\/___/. -'// # * ##==== '-. ____'. ___\_____/___. -'___. -'= ==#* #' = --- = '#*#~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~ ####* # Buddha bless never has a BUG #*##*######################## ########################### */package com. uit. commons; import android. content. context; import android. graphics. bitmap; import android. view. view; import android. widget. checkBox; import android. widget. imageView; import android. widget. textView; import com. uit. commons. utils. viewFinder;/*** this is a general ViewHolder. It will load the item View of the AbsListView subclass and set item * vi The sub-views in ew are cached and indexed so that you can easily obtain these sub-views, reducing code duplication. ** @ Author mrsimple */public class CommonViewHolder {/*** constructor ** @ param context Context * @ param layoutId resource layout of the Item View of ListView, GridView, or other AbsListVew subclass id */protected CommonViewHolder (Context context, int layoutId) {// initialize the layout and load ContentView ViewFinder. initContentView (context, layoutId); // store ViewHolder In the tag of ContentView ViewFinder. getContentView (). setTag (this);}/*** get CommonViewHolder, When convertView is empty, the item view is loaded from the layout xml, * and the CommonViewHolder is set to the tag of convertView, which is easy to reuse convertView. ** @ param context * @ param convertView Item view * @ param layoutId layout resource id, such as R. layout. my_listview_item. * @ return common CommonViewHolder instance */public static CommonViewHolder getViewHolder (Context context, View convertView, int layoutId) {if (convertView = null) {return new CommonViewHolder (contex T, layoutId);} return (CommonViewHolder) convertView. getTag ();}/*** @ return convertView of the current item. Load */public View getConvertView () {return ViewFinder in the constructor. getContentView ();} /*** set the text content for TextView with the id textViewId ** @ param textViewId view id * @ param text the text to be set */public void setTextForTextView (int textViewId, charSequence text) {TextView textView = ViewFinder. findViewById (textViewId); if (text View! = Null) {textView. setText (text) ;}}/*** set image ** @ param imageViewId ImageView id for ImageView, such as R. id. my_imageview * @ param drawableId the id of the Drawable image, for example, R. drawable. my_photo */public void setImageForView (int imageViewId, int drawableId) {ImageView imageView = ViewFinder. findViewById (imageViewId); if (imageView! = Null) {imageView. setImageResource (drawableId);}/*** set the image ** @ param imageViewId ImageView id for ImageView, such as R. id. my_imageview * @ param bmp Bitmap image */public void setImageForView (int imageViewId, Bitmap bmp) {ImageView imageView = ViewFinder. findViewById (imageViewId); if (imageView! = Null) {imageView. setImageBitmap (bmp);}/*** set whether to select ** @ param checkViewId CheckBox id * @ param isCheck */public void setCheckForCheckBox (int checkViewId, boolean isCheck) {CheckBox checkBox = ViewFinder. findViewById (checkViewId); if (checkBox! = Null) {checkBox. setChecked (isCheck );}}}


ViewFinder helper class

/*** View finder for convenient search of views. You need to call initContentView when using it, * pass in the Context and layout id, and then use findViewById to obtain the desired view *. findViewById is a generic method, the returned view directly belongs to the type you receive, and does not require forced type conversion. for example, * we used to find a TextView in the Activity as follows: * TextView textView = (TextView) findViewById (viewId); * if there are many controls on the page, there will be a lot of type conversion, while ViewFinder removes the need for type conversion. * example: * TextView textView = ViewFinder. findViewById (viewId); ** @ author mrsimple */public final class ViewFinder {/*** LayoutInflater */static LayoutInflater mInflater; /*** sub View Map of each view */private static SparseArray
 
  
MViewMap = new SparseArray
  
   
();/*** Content View */static View mContentView;/*** initialize ViewFinder to obtain the ContentView of the page. ** @ param context * @ param layoutId */public static void initContentView (Context context, int layoutId) {mInflater = LayoutInflater. from (context); mContentView = mInflater. inflate (layoutId, null, false); if (mInflater = null | mContentView = null) {throw new RuntimeException ("ViewFinder init failed, mInflater = null | mContentView = null. ") ;}}/***** @ return */public static View getContentView () {return mContentView ;} /*** @ param viewId * @ return */@ SuppressWarnings ("unchecked") public static
   
    
T findViewById (int viewId) {// first query from the view map. If some cache is available, use it directly. Otherwise, find View tagetView = mViewMap from mContentView. get (viewId); if (tagetView = null) {tagetView = mContentView. findViewById (viewId); mViewMap. put (viewId, tagetView);} return tagetView = null? Null: (T) mContentView. findViewById (viewId );}}
   
  
 

The code is on Github. Click here.

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.