A detailed explanation of the omnipotent adapter in Android

Source: Internet
Author: User

A detailed explanation of the omnipotent adapter in Android

A detailed explanation of the omnipotent adapter in Android
In Android development, adapters are very useful, especially in efficiency optimization. Besides using ViewHolder to reuse views, if there are many ListView or a ListView with many View components, it is not good to read the code. ConsideringOptimization and common aspects, I encapsulatedViewHolder class and encapsulation of Adapter class into commonWill bring great convenience for future development.
The performance improvements in the adapter are as follows:
1. Use convertView

Using the Recycler mechanism of Android and convertView to recycle the View, the efficiency is substantially improved. It is time-consuming to create a View. Therefore, the convertView passed in by the getview method should be fully utilized! = Null.

2. Use ViewHolder

ViewHolder encapsulates the view to be cached. The setTag of convertView caches the view for the next call. When the layout in your listview is diversified, the effect of viewholder is obvious, and the efficiency is improved again. The findViewById () method of View is also time-consuming. Therefore, you must consider calling it only once. Then you can use the View. getTag () method to obtain the ViewHolder object.

3. Use ViewHolder elegantly

When ViewHolder is used, the findViewById is repeated each time, and the View definition is added to the ViewHolder over and over again. If there are more views, isn't it annoying, the base-adapter-helper class library seems to solve this problem perfectly.

The design idea is to use SparseArray to store view references, instead of the original ViewHolder, without declaring a lot of views, which is concise and clear.

(1) ViewHolder class encapsulation is as follows: ViewHolder class:

Package com. chengdong. su. baseadapter. util; import android. content. context; import android. util. log; import android. util. sparseArray; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. imageView; import android. widget. textView; /*** the common object of the ViewHolder *** @ author scd **/public class ViewHolder {/** the object of the TAG */private String TAG = getClass (). getSimpleName ();/** the object of the view */private SparseArray
  
   
MViews;/** the object of the position */private int mPosition;/** the object of the converview */private View mConvertView; /***** constructor ** @ param context * @ param parent * @ param layoutId * @ param position */public ViewHolder (Context context, ViewGroup parent, int layoutId, int position) {super (); this. mPosition = position; this. mViews = new SparseArray
   
    
(); MConvertView = LayoutInflater. from (context ). inflate (layoutId, parent, false); mConvertView. setTag (this );} /*** get the object of the ViewHolder ** @ param context * @ param convertView * @ param parent * @ param layoutId * @ param position * @ return */public static ViewHolder getViewHolder (Context context, view convertView, ViewGroup parent, int layoutId, int position) {if (convertView = null) {return new ViewHolder (context, parent, layoutId, position );} else {ViewHolder holder = (ViewHolder) convertView. getTag (); // modify the location change holder. mPosition = position; Log. d (getViewHolder, getViewHolder: position: ---> + position); return holder ;}} /*** find the view by the viewId ** @ param viewId * @ return */@ SuppressWarnings (unchecked) public
    
     
T findView (int viewId) {View view = mViews. get (viewId); if (view = null) {view = mConvertView. findViewById (viewId); // Add the View object mViews. put (viewId, view);} return (T) view;}/*** get the object of the convertView ** @ return */public View getConvertView () {return mConvertView;} public int getPosition () {return mPosition ;} /*** set the value for TextView ** @ param viewId * @ param text * @ return */public ViewHolder setText (int viewId, String text) {TextView textView = findView (viewId); textView. setText (text); return this;}/*** set the value for ImageView ** @ param viewId * @ param resId * @ return */public ViewHolder setImageResource (int viewId, int resId) {ImageView view = findView (viewId); view. setImageResource (resId); return this;} // The auxiliary method of the todo View to be written}
    
   
  

(2) The implementation of common classes of CommonAdapter is as follows:

Package com. chengdong. su. baseadapter. util; import java. util. list; import android. r. integer; import android. content. context; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import com. chengdong. su. baseadapter. r; public abstract class CommonAdapter
  
   
Extends BaseAdapter {/** Context */protected Context mContext;/** data source */protected List
   
    
MData; private int mLayoutId; public CommonAdapter (Context mContext, int layoutId) {super (); this. mContext = mContext; this. mLayoutId = layoutId;} @ Override public int getCount () {return mData. size () ;}@ Override public T getItem (int position) {return (T) (mData = null? 0: mData. get (position) ;}@ Override public long getItemId (int position) {return position ;}@ Override public View getView (int position, View convertView, ViewGroup parent) {ViewHolder holder = ViewHolder. getViewHolder (mContext, convertView, parent, mLayoutId, position); convert (holder, getItem (position); return holder. getConvertView ();}/*** Set Data */public abstract void setData (List
    
     
Data);/*** Method for assigning data to View */public abstract void convert (ViewHolder holder, T item );}
    
   
  

(3) implementation of the MyAdapter class:

Package com. chengdong. su. baseadapter. adapter; import java. util. arrayList; import java. util. list; import android. content. context; import android. view. view; import android. widget. checkBox; import com. chengdong. su. baseadapter. r; import com. chengdong. su. baseadapter. bean. bean; import com. chengdong. su. baseadapter. util. commonAdapter; import com. chengdong. su. baseadapter. util. viewHolder;/*** common ViewHolder ** @ author scd **/public class MyAdapter extends CommonAdapter
  
   
{Private List
   
    
MList = new ArrayList
    
     
(); Public MyAdapter (Context mContext) {super (mContext, R. layout. item_listview);} @ Override public void setData (List
     
      
Data) {mData = data; notifyDataSetChanged () ;}@ Override public void convert (final ViewHolder holder, Bean item) {// chained programming holder. setText (R. id. TV _title, item. getTitle ()). setText (R. id. TV _desc, item. getDesc ()). setText (R. id. TV _time, item. getTime ()). setText (R. id. TV _phone, item. getPhone (); // checkBox reuse solution to content disorder final CheckBox checkBox = holder. findView (R. id. cb_select); // the checkBox is not selected by default. setChecked (false); if (mList. contains (holder. getPosition () {checkBox. setChecked (true);} checkBox. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {if (checkBox. isChecked () {mList. add (Integer) holder. getPosition ();} else {mList. remove (Integer) holder. getPosition ());}}});}}
     
    
   
  

(4) The MainActivity class is implemented as follows:

package com.chengdong.su.baseadapter;import java.util.ArrayList;import java.util.List;import com.chengdong.su.baseadapter.adapter.MyAdapter;import com.chengdong.su.baseadapter.bean.Bean;import android.app.Activity;import android.os.Bundle;import android.widget.ListView;public class MainActivity extends Activity {    private ListView mListView;    private MyAdapter mAdapter;    private List
  
    mData;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();    }    private void initView() {        mListView = (ListView) findViewById(R.id.lv_show);        mAdapter = new MyAdapter(MainActivity.this);        initData();        mAdapter.setData(mData);        mListView.setAdapter(mAdapter);    }    private void initData() {        mData = new ArrayList
   
    ();        Bean bean = new Bean(1, 2, 3, 4);        for (int i = 0; i < 11; i++) {            mData.add(bean);        }    }}
   
  

(5) The activity_main class is implemented as follows:


      
   
  

(6) implementation of the item_listview class:


  
  
   
    
     
      
       
      
     
    
   
  

Note:
android:descendantFocusability=blocksDescendants
android:focusable=false

It is a solution to preemptible focus of items due to the existence of checkbox or other controls: the solution item cannot be selected and clicked.
// The solution to content disorder caused by reuse of checkBox is as follows:

Final CheckBox checkBox = holder. findView (R. id. cb_select); // the checkBox is not selected by default. setChecked (false); if (mList. contains (holder. getPosition () {checkBox. setChecked (true);} checkBox. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {if (checkBox. isChecked () {mList. add (Integer) holder. getPosition ();} else {mList. remove (Integer) holder. getPosition ());}}});

 

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.