어댑터 BaseAdapter 캡슐화로 개발 효율성 향상

7331 단어
BaseAdapter는 우리가 공부하기 시작하면 알아야 할 어댑터로 주로 ListView, GridView 등 다른 목록 내용을 보여주는 데 사용된다.오늘 저는 주로 제가 포장한 BaseAdapter를 제공하고 실용적인 종류를 여러분께 드리며 중복되는 작업량을 줄이고 코드를 직접 붙입니다.
package com.tangyx.home.factory;

import android.content.Context;
import android.os.Build;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Field;
import java.util.List;


/**
 * Created by tangyx on 15/9/21.
 *
 */
public abstract class BaseHomeAdapter extends BaseAdapter {
    public OnChildClickListener mChildClickListener;
    public JSONArray mArrays;
    public List mList;
    public Context mContext;
    private ViewHolder viewHolder;

    public BaseHomeAdapter(Context context) {
        this.mContext = context;
    }

    public BaseHomeAdapter(Context context, JSONArray arrays) {
        this(context);
        this.mArrays = arrays;
    }

    public BaseHomeAdapter(Context context, List list) {
        this(context);
        this.mList = list;
    }

    @Override
    public int getCount() {
        if (mList != null) {
            return mList.size();
        }
        if (mArrays != null) {
            return mArrays.length();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        try {
            if (mList != null) {
                return mList.get(position);
            }
            return mArrays.get(position);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(mContext);
                convertView = onBindView(inflater);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            onBindData(position, convertView, parent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }

    /**
     *     
     */
    private class ViewHolder {
        View view;
        SparseArray holderArray;

        ViewHolder(View view) {
            this.view = view;
            holderArray = new SparseArray<>();
        }
    }

    /**
     *   item  
     * @param inflater
     * @return
     * @throws Exception
     */
    public abstract View onBindView(LayoutInflater inflater) throws Exception;

    /**
     *   item      
     * @param position
     * @param convertView
     * @param parent
     * @throws Exception
     */
    public abstract void onBindData(int position, View convertView, ViewGroup parent) throws Exception;

    /**
     *        view
     *
     * @param id
     * @param 
     * @return
     */
    public  T obtainView(int id) {
        return obtainView(viewHolder.view,id,0);
    }
    public  T obtainView(View layout,int id,int position) {
        View view = viewHolder.holderArray.get(layout.getId()+id+position);
        if (null != view) {
            return (T) view;
        }
        view =layout.findViewById(id);
        if (null == view) {
            return null;
        }
        viewHolder.holderArray.put(layout.getId()+id+position, view);
        return (T) view;
    }
    /**
     *        
     */
    public  T get(int index) {
        Object val;
        if (mArrays != null) {
            try {
                val = mArrays.get(index);
                return (T) val;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (mList != null) {
            val = mList.get(index);
            return (T) val;
        }
        return null;
    }

    /**
     *     
     */
    public Object remove(int index) {
        if (mList != null) {
            return mList.remove(index);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            return mArrays.remove(index);
        }
        Field valuesField;
        try {
            valuesField = JSONArray.class.getDeclaredField("values");
            valuesField.setAccessible(true);
            List values = (List) valuesField.get(mArrays);
            if (index < values.size()) {
                return values.remove(index);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *       
     */
    public void removeAll() {
        if (mArrays != null) {
            mArrays = new JSONArray();
        }
        if (mList != null) {
            mList.clear();
        }
        notifyDataSetChanged();
    }

    /**
     *     item
     * @param object
     */
    public void addItem(Object object) {
        if (mArrays != null) {
            mArrays.put(object);
        }
        if (mList != null) {
            mList.add(object);
        }
    }

    /**
     *        
     * @param jsonArray
     */
    public void replaceAll(JSONArray jsonArray) {
        this.mArrays = jsonArray;
        this.mList = null;
        notifyDataSetChanged();
    }

    /**
     *        
     * @param list
     */
    public void replaceAll(List list) {
        this.mList = list;
        this.mArrays = null;
        notifyDataSetChanged();
    }

    /**
     * item         
     * @param mChildClickListener
     */
    public void setChildClickListener(OnChildClickListener mChildClickListener) {
        this.mChildClickListener = mChildClickListener;
    }

    public interface OnChildClickListener {
        void onChildClick(View... view);
    }

}

또한 List 컬렉션과 Json Array 두 가지 유형을 지원하며 추가 컬렉션이 있으면 필요에 따라 직접 변경할 수 있습니다. 다음은 사용에 대한 설명입니다.
package com.tangyx.home.factory;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.tangyx.home.demo.R;

import java.util.List;

/**
* Created by tangyx on 2016/12/16.
*
*/

public class SimpleAdapter extends BaseHomeAdapter {

   public SimpleAdapter(Context context, List list) {
       super(context, list);
   }

   @Override
   public View onBindView(LayoutInflater inflater) throws Exception {
       //       item  
       return inflater.inflate(R.layout.adapter_item,null);
   }

   @Override
   public void onBindData(int position, View convertView, ViewGroup parent) throws Exception {
       //  item     
       TextView mName = obtainView(R.id.name);
       //    list     
       Simple mSimple = get(position);
   }
}

간단합니다. BaseHomeAdapter를 직접 상속하면 됩니다.총결산: 많은 때에 쓴 코드가 많아지면 코드를 어떻게 하면 더 좋고 완벽하게 만들 수 있는지, 개발 효율을 더욱 효율적으로 할 수 있는지를 정리하게 될 것이다. 나는 간단하면서도 실용적인 것을 공유하는 것을 좋아한다.

좋은 웹페이지 즐겨찾기