Android开发自定义Listview的Adapter基类以及通用ViewHolder的写法

简单的写一个Adapter基类,不用每次写adapter都调用一堆方法。


import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

public abstract class ListBaseAdapter extends BaseAdapter {
    protected List _data;
    public ListState listState = ListState.NONE;
    //这里是下拉刷新的状态码
    public enum ListState {
        NONE, REFRESHING, LOADMOREING;
    }

    public List getData() {
        return _data == null ? (_data = new ArrayList()) : _data;
    }

    @SuppressWarnings("rawtypes")
    public void setData(List data) {
        _data = data;
        notifyDataSetChanged();
    }

    @Override
    public boolean isEmpty() {
        if (_data == null) {
            return true;
        } else {
            if (_data.size() == 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    @Override
    public int getCount() {
        if (_data == null) {
            return 0;
        }
        return _data.size();
    }

    @Override
    public Object getItem(int arg0) {
        if (_data != null && _data.size() > arg0) {
            return _data.get(arg0);
        }
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO 自动生成的方法存根
        return arg0;
    }

}

然后再简单来搞个通用的ViewHolder,省得每次都要写一堆Viewholder


import android.util.SparseArray;
import android.view.View;
import android.widget.Adapter;

public class ViewHolder {

    private final SparseArray views;
    private View convertView;
    private Adapter adapter;

    public ViewHolder(View convertView) {
        this.views = new SparseArray();
        this.convertView = convertView;
    }

    public  T getView(int viewId) {
        View view = views.get(viewId);
        if (view == null) {
            view = convertView.findViewById(viewId);
            views.put(viewId, view);
        }
        return (T) view;
    }

    public Adapter getAdapter() {

        return adapter;
    }

    public void setAdapter(Adapter adapter) {
        this.adapter = adapter;
    }
}

要调用的时候,直接在adapter的getview里调用:

      ViewHolder holder;
      if (convertView == null) {
          convertView = mInflater.inflate(R.layout.listitem_ads, parent, false);
          holder = new ViewHolder(convertView);
          convertView.setTag(holder);
      } else {
          holder = (ViewHolder) convertView.getTag();
      }
   View v_view = holder.getView(R.id.v_view);


你可能感兴趣的:(Android开发相关)