Android小框架之更简易的ArrayAdapter

BaseAdapter是Android开发中使用频率很高一个ListView的基础Adapter,再此之上Android官方提供另外一个ArrayAdapter,一看它的名字就知道是封装了List集合的一个简易Adapter。Adapter经常搭配ViewHolder来使用,可以高效的复用已经生成的View,虽然ArrayAdapter已经很便捷,可是开发中,我们总要编写与ViewHolder连接的代码,懒惰是开发者的天性,所以我们在这里就把它抽象出来,让ArrayAdapter更便捷。

干货Gist点这里
MagicArrayAdapter.java

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

/**
 * @author solo
 */
public abstract class MagicArrayAdapter<T> extends ArrayAdapter<T> {

    private final LayoutInflater mInflater;
    private final int mResource;

    public MagicArrayAdapter(Context context, int resource) {
        super(context, resource);
        mResource = resource;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        MagicViewHolder<T> h;
        if (convertView == null) {
            convertView = mInflater.inflate(mResource, parent, false);
            h = getViewHolder(position, convertView, parent);
            convertView.setTag(h);
        } else {
            h = (MagicViewHolder<T>) convertView.getTag();
        }
        h.populateView(position, convertView, parent, getItem(position));
        return convertView;
    }

    abstract public MagicViewHolder<T> getViewHolder(int position, View convertView, ViewGroup parent);

}

MagicViewHolder.java

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

/**
 * @author solo
 */
public abstract class MagicViewHolder<T>  {

    public MagicViewHolder(View view) {
      
    }

    /**
     * 更新AdapterView的每个item
     */
    abstract public void populateView(int position, View convertView, ViewGroup parent, T item);
    
}

使用例子:

// Adapter
class YourAdapter extends MagicArrayAdapter<YourEntity> {

    public YourAdapter(Context context) {
        super(context, R.layout.your_layout);
    }

    @Override
    public MagicViewHolder< YourEntity > getViewHolder(int position, View convertView, ViewGroup parent) {
        return new ViewHolder(convertView, this);
    }

}

// ViewHolder
static class ViewHolder extends MagicViewHolder<YourEntity> {

    public ViewHolder(View view) {
        // hold your view
    }

    @Override
    public void populateView(int position, View convertView, ViewGroup parent, YourEntity item) {
        // do something
    }
}

代码很简单,相信你们一定一眼就明白。

感谢各位读者,喜欢的话点个赞吧,有哪里不懂的也可以在下方留言。:)

转载请附上本文地址

    原文作者:SoloHo
    原文地址: https://www.jianshu.com/p/b0f0927d0c54
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞