可复用的自定义BaseAdapter

复制代码
public class MyAdapter extends BaseAdapter {

    private Context mContext;
    private LinkedList<Data> mData;

    public MyAdapter() {
    }

    public MyAdapter(LinkedList<Data> mData, Context mContext) {
        this.mData = mData;
        this.mContext = mContext;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
            holder = new ViewHolder();
            holder.img_icon = (ImageView) convertView.findViewById(R.id.img_icon);
            holder.txt_content = (TextView) convertView.findViewById(R.id.txt_content);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.img_icon.setImageResource(mData.get(position).getImgId());
        holder.txt_content.setText(mData.get(position).getContent());
        return convertView;
    }

    //添加一个元素
    public void add(Data data) {
        if (mData == null) {
            mData = new LinkedList<>();
        }
        mData.add(data);
        notifyDataSetChanged();
    }

    //往特定位置,添加一个元素
    public void add(int position,Data data){
        if (mData == null) {
            mData = new LinkedList<>();
        }
        mData.add(position, data);
        notifyDataSetChanged();
    }

    public void remove(Data data) {
        if(mData != null) {
            mData.remove(data);
        }
        notifyDataSetChanged();
    }

    public void remove(int position) {
        if(mData != null) {
            mData.remove(position);
        }
        notifyDataSetChanged();
    }

    public void clear() {
        if(mData != null) {
            mData.clear();
        }
        notifyDataSetChanged();
    }

    private class ViewHolder {
        ImageView img_icon;
        TextView txt_content;
    }

}

将Entity设置成泛型

传递过来的Entitiy实体类可能千奇百怪,比如有Person,Book,Wether等,所以将Entity设置成泛型,代码如下:

public class MyAdapter<T> extends BaseAdapter {

private Context mContext;

private LinkedList<T> mData;

public MyAdapter() {

}

public MyAdapter(LinkedList<T> mData, Context mContext) {

this.mData = mData;

this.mContext = mContext;

}

@Override

public int getCount() {

return mData.size();

}

@Override

public Object getItem(int position) {

return null;

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder = null;

if (convertView == null) {

convertView = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);

holder = new ViewHolder();

holder.img_icon = (ImageView) convertView.findViewById(R.id.img_icon);

holder.txt_content = (TextView) convertView.findViewById(R.id.txt_content);

convertView.setTag(holder);

} else {

holder = (ViewHolder) convertView.getTag();

}

holder.img_icon.setImageResource(mData.get(position).getImgId());

holder.txt_content.setText(mData.get(position).getContent());

return convertView;

}

//添加一个元素

public void add(T data) {

if (mData == null) {

mData = new LinkedList<>();

}

mData.add(data);

notifyDataSetChanged();

}

//往特定位置,添加一个元素

public void add(int position,T data){

if (mData == null) {

mData = new LinkedList<>();

}

mData.add(position, data);

notifyDataSetChanged();

}

public void remove(T data) {

if(mData != null) {

mData.remove(data);

}

notifyDataSetChanged();

}

public void remove(int position) {

if(mData != null) {

mData.remove(position);

}

notifyDataSetChanged();

}

public void clear() {

if(mData != null) {

mData.clear();

}

notifyDataSetChanged();

}

private class ViewHolder {

ImageView img_icon;

TextView txt_content;

}

}

ViewHolder类的升级改造:

我们先来看看前面我们的ViewHolder干了什么? 答:findViewById,设置控件状态; 下面我们想在完成这个基础上,将getView()方法大部分的逻辑写到ViewHolder类里, 这个ViewHolder要做的事:

  • 定义一个查找控件的方法,我们的思路是通过暴露公共的方法,调用方法时传递过来 控件id,以及设置的内容,比如TextView设置文本: public ViewHolder setText(int id, CharSequence text){文本设置}
  • 将convertView复用部分搬到这里,那就需要传递一个context对象了,我们把需要获取 的部分都写到构造方法中!
  • 写一堆设置方法(public),比如设置文字大小颜色,图片背景等!

最终BaseAdapter :

复制代码
public abstract class MyAdapter<T> extends BaseAdapter {

    private ArrayList<T> mData;
    private int mLayoutRes;           //布局id
    private View emptyView;
    private Context context;

    public MyAdapter() {
    }

    public MyAdapter(Context context,ArrayList<T> mData, int mLayoutRes) {
        this.context=context;
        this.mData = mData;
        this.mLayoutRes = mLayoutRes;
        updateEmptyViewVisibility();
    }
复制代码
//    <include
//    android:id="@+id/empty_view"
//    layout="@layout/empty_list_item"
//    android:layout_width="match_parent"
//    android:layout_height="match_parent"
//    />
//    private View emptyView;
//    this.emptyView = findViewById(R.id.empty_view);
复制代码
    public MyAdapter(Context context,ArrayList<T> mData, int mLayoutRes,View emptyView) {
        this.context=context;
        this.mData = mData;
        this.mLayoutRes = mLayoutRes;
        this.emptyView=emptyView;
        updateEmptyViewVisibility();
    }
    // 更新空数据提示布局的可见性
    
复制代码
private void updateEmptyViewVisibility() {
    if (emptyView != null) {
        if (mData.size() == 0) {
            emptyView.setVisibility(View.VISIBLE);
        } else {
            emptyView.setVisibility(View.GONE);
        }
    }
}
    @Override
    public int getCount() {
        return mData != null ? mData.size() : 0;
    }

    @Override
    public T getItem(int position) {
        return mData.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder =null;
//        if(mData.size()<=0) {
//           Logger.d("mData.size()<=0");
//            convertView = LayoutInflater.from(context).
//                    inflate(R.layout.empty_list_item, parent, false);
//            return convertView;
            holder = ViewHolder.bind(context, convertView, parent, R.layout.empty_list_item
                    , position);
//        }
//        else{
            holder = ViewHolder.bind(context, convertView, parent, mLayoutRes
                    , position);
//        }

//        ViewHolder holder = ViewHolder.bind(parent.getContext(), convertView, parent, mLayoutRes
//                , position);
        bindView(holder, getItem(position));
        return holder.getItemView();
    }


    //定义一个抽象方法,完成ViewHolder与Data数据集的绑定

    public abstract void bindView(ViewHolder holder, T obj);

    //添加一个元素
    public void add(T data) {
        if (mData == null) {
            mData = new ArrayList<>();
        }
        mData.add(data);
        notifyDataSetChanged();
    }

    //往特定位置,添加一个元素
    public void add(int position, T data) {
        if (mData == null) {
            mData = new ArrayList<>();
        }
        mData.add(position, data);
        notifyDataSetChanged();
    }

    public void remove(T data) {
        if (mData != null) {
            mData.remove(data);
        }
        notifyDataSetChanged();
    }

    public void remove(int position) {
        if (mData != null) {
            mData.remove(position);
        }
        notifyDataSetChanged();
    }

    public void clear() {
        if (mData != null) {
            mData.clear();
        }
        notifyDataSetChanged();
    }
复制代码
public void update(int position, T data) {
    if (mData == null) {
        return;
    }
    mData.set(position,data);
    notifyDataSetChanged();
}
复制代码
    public static class ViewHolder {

        private SparseArray<View> mViews;   //存储ListView 的 item中的View
        private View item;                  //存放convertView
        private int position;               //游标
        private Context context;            //Context上下文

        //构造方法,完成相关初始化
        private ViewHolder(Context context, ViewGroup parent, int layoutRes) {
            mViews = new SparseArray<>();
            this.context = context;
            View convertView = LayoutInflater.from(context).inflate(layoutRes, parent, false);
            convertView.setTag(this);
            item = convertView;
        }

        //绑定ViewHolder与item
        public static ViewHolder bind(Context context, View convertView, ViewGroup parent,
                                      int layoutRes, int position) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder(context, parent, layoutRes);
            } else {
                holder = (ViewHolder) convertView.getTag();
                holder.item = convertView;
            }
            holder.position = position;
            return holder;
        }


        /**
         * 根据id获取集合中保存的控件
         */

        @SuppressWarnings("unchecked")
        public <T extends View> T getView(int id) {
            T t = (T) mViews.get(id);
            if (t == null) {
                t = (T) item.findViewById(id);
                mViews.put(id, t);
            }
            return t;
        }


        /**
         * 获取当前条目
         */
        public View getItemView() {
            return item;
        }

        /**
         * 获取条目位置
         */
        public int getItemPosition() {
            return position;
        }

        /**
         * 设置文字
         */
        public ViewHolder setText(int id, CharSequence text) {
            View view = getView(id);
            if (view instanceof TextView) {
                ((TextView) view).setText(text);
            }
            return this;
        }

        /**
         * 设置图片
         */
        public ViewHolder setImageResource(int id, int drawableRes) {
            View view = getView(id);
            if (view instanceof ImageView) {
                ((ImageView) view).setImageResource(drawableRes);
            } else {
                view.setBackgroundResource(drawableRes);
            }
            return this;
        }


        /**
         * 设置点击监听
         */
        public ViewHolder setOnClickListener(int id, View.OnClickListener listener) {
            getView(id).setOnClickListener(listener);
            return this;
        }

        /**
         * 设置可见
         */
        public ViewHolder setVisibility(int id, int visible) {
            getView(id).setVisibility(visible);
            return this;
        }

        /**
         * 设置标签
         */
        public ViewHolder setTag(int id, Object obj) {
            getView(id).setTag(obj);
            return this;
        }

        //其他方法可自行扩展
        
复制代码
public ViewHolder setwidth(int id, int iwidth) {
    ViewGroup.LayoutParams params=getView(id).getLayoutParams();
    params.width=iwidth;
    View view = getView(id);
    view.setLayoutParams(params);

    if (view instanceof TextView) {
        ((TextView) view).setSingleLine(true);
        //((TextView) view).setEllipsize(null);//隐藏省略号
    }
    return this;
}

/**
 * 设置字体大小
 * @param id
 * @param size
 * @return
 */
public ViewHolder settextsize(int id, int size) {
    View view = getView(id);
    if (view instanceof TextView) {
        ((TextView) view).setTextSize(size);
    }
    return this;
}

/**
 * 设置显示隐藏及宽度
 * @param id
 * @param visible
 * @param iwidth
 * @return
 */
public ViewHolder setVisibility(int id, int visible,int iwidth) {
    if(visible==0)
    {
        getView(id).setVisibility(View.GONE);
    }
    else {
        getView(id).setVisibility(View.VISIBLE);

        ViewGroup.LayoutParams params=getView(id).getLayoutParams();
        params.width=iwidth;
        View view = getView(id);
        view.setLayoutParams(params);
    }

    return this;
}

public ViewHolder setText(int id, CharSequence text,int iwidth) {
    View view = getView(id);
    if (view instanceof TextView) {
        ((TextView) view).setText(text);
        ((TextView) view).setVisibility(View.VISIBLE);
    }
    ViewGroup.LayoutParams params=getView(id).getLayoutParams();
    params.width=iwidth;
    view.setLayoutParams(params);
    return this;
}
复制代码
    }

}
复制代码

就是上面有两个列表,布局不一样,但是我只使用一个BaseAdapter类来完成上述效果!

MainActivity.java

public class MainActivity extends AppCompatActivity {

private Context mContext;

private ListView list_book;

private ListView list_app;

private MyAdapter<App> myAdapter1 = null;

private MyAdapter<Book> myAdapter2 = null;

private List<App> mData1 = null;

private List<Book> mData2 = null;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mContext = MainActivity.this;

init();

}

private void init() {

list_book = (ListView) findViewById(R.id.list_book);

list_app = (ListView) findViewById(R.id.list_app);

//数据初始化

mData1 = new ArrayList<App>();

mData1.add(new App(R.mipmap.iv_icon_baidu,"百度"));

mData1.add(new App(R.mipmap.iv_icon_douban,"豆瓣"));

mData1.add(new App(R.mipmap.iv_icon_zhifubao,"支付宝"));

mData2 = new ArrayList<Book>();

mData2.add(new Book("《第一行代码Android》","郭霖"));

mData2.add(new Book("《Android群英传》","徐宜生"));

mData2.add(new Book("《Android开发艺术探索》","任玉刚"));

//Adapter初始化

myAdapter1 = new MyAdapter<App>((ArrayList)mData1,R.layout.item_one) {

@Override

public void bindView(ViewHolder holder, App obj) {

holder.setImageResource(R.id.img_icon,obj.getaIcon());

holder.setText(R.id.txt_aname,obj.getaName());

}

};

myAdapter2 = new MyAdapter<Book>((ArrayList)mData2,R.layout.item_two) {

@Override

public void bindView(ViewHolder holder, Book obj) {

holder.setText(R.id.txt_bname,obj.getbName());

holder.setText(R.id.txt_bauthor,obj.getbAuthor());

}

};

//ListView设置下Adapter:

list_book.setAdapter(myAdapter2);

list_app.setAdapter(myAdapter1);

}

}

相关推荐
少说多做3431 天前
Android 使用 LiveData/OnCheckedChangeListener 来监听变量变化
android·java·android-studio
B.-8 天前
Flutter 应用在真机上调试的流程
android·flutter·ios·xcode·android-studio
朱某人199514 天前
AndroidStudio 加载grade失败问题解决
android-studio
PleaSure乐事19 天前
AndroidStudio通过Bundle进行数据传递
android·java·android studio·android-studio·移动应用开发
孑么21 天前
GDPU Andriod移动应用 Fragment碎片与简易版的新闻应用
android·xml·java·kotlin·gradle·android-studio
西红柿计算机毕设24 天前
基于安卓Android的健康饮食系统APP(源码+文档+部署+讲解)
大数据·数据库·vue.js·spring boot·python·android-studio
天神哥哥啊1 个月前
AndroidStudio部署多渠道打包环境(一)
android·游戏·android-studio
天神哥哥啊1 个月前
git清理本地.git文件夹下的缓存
android·git·游戏·unity·android-studio
布丁椰奶冻1 个月前
【移动应用开发】Android持久化技术
android·数据库·android studio·android-studio
我命由我123451 个月前
6-2.Android 对话框之基础对话框问题清单(UI 线程问题、外部取消、冲突问题、dismiss 方法与 hide 方法)
android·java·ui·java-ee·android studio·安卓·android-studio