Android universal Adapter (2) Encapsulation Adapter and androidadapter
This article continues with the previous article. Before reading this article, you need to understand the ViewHolder encapsulation.
Android universal adapter (1) Encapsulation ViewHolder
Encapsulate Adapter
Adapter here is mainly to make a simple encapsulation to inherit the BaseAdapter class. Several methods need to be overwritten by default. For example, getCount and getItemID. The Adapter we write will repeat these methods each time, and the returned content is almost the same, so it can be encapsulated in the parent class. You can use generics to virtualize an object class to achieve the list effect. When this class is used, it is OK to pass a real object class. The following is the source code of the encapsulated Adapter. In general, we want to name it BaseAdapter. Here we use MyBaseAdapter to distinguish it from the system BaseAdapter.
Public abstract class MyBaseAdapter <T> extends BaseAdapter {protected LayoutInflater mInflater; protected Context mContext; protected List <T> mDatas; protected final int mLayoutId; public MyBaseAdapter (Context context Context, list <T> mDatas, int mLayoutId) {mInflater = LayoutInflater. from (context); this. mContext = context; this. mDatas = mDatas; this. mLayoutId = mLayoutId;} @ Overridepublic int getCount () {return mDatas. size () ;}@ Overridepublic Object getItem (int position) {return mDatas. get (position) ;}@ Overridepublic long getItemId (int position) {return position ;}@ Overridepublic View getView (int position, View convertView, ViewGroup parent) {// instantiate a viewHolderViewHolder viewHolder = ViewHolder. get (mContext, convertView, parent, mLayoutId, position); holdItem (viewHolder, mDatas. get (position); return viewHolder. getConvertView ();} public abstract void holdItem (ViewHolder holder, T item );}
The encapsulated Adapter is used to implement the list Adapter with only one TextView in the previous article. The source code is as follows:
public class TestAdapter extends MyBaseAdapter<String>{public TestAdapter(Context context, List<String> mDatas, int mLayoutId) {super(context, mDatas, mLayoutId); }@Overridepublic void holdItem(ViewHolder holder, String item) {TextView view = holder.getView(R.id.text_title); <span style="white-space:pre"></span>view.setText(item); }}
The current adapter looks very simple and efficient. Just like it.
The Adapter is the same as the normal one. Set listview directly.
private void initListView() {mListView = (ListView) findViewById(R.id.list_main);mAdapter = new TestAdapter(this, mDatas,R.layout.item_1);mListView.setAdapter(mAdapter);}
If you are interested in learning, join the QQ Group 372647271 IsCoding studio.
Source code download
Copyright Disclaimer: This article is an original article by the blogger. For more information, see the source. Blog: http://blog.csdn.net/androidiscoding