对base-adapter-helper的简单分析
在微博上看到了这篇Android ListView适配器应该这样写,受益匪浅。
于是依据文章结尾的介绍来到了base-adapter-helper的github,地址:https://github.com/JoanZapata/base-adapter-helper
然后下载看看,我等小菜也来分析分析。
源代码包括4个文件:
BaseAdapterHelper.java
BaseQuickAdapter.java
EnhancedQuickAdapter.java
QuickAdapter.java
其中最基本的是前两个。
先看BaseAdapterHelper。第一个文章也写了,这个类是替代viewHolder的。进一步封装优化的产物,包括一些封装好的经常使用功能,比方imageView图片的载入,文本框改动文本,给控件加入各种事件等等。
先上代码,凝视我自己加的:
package com.joanzapata.android;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.util.Linkify;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.*;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
public class BaseAdapterHelper {
private final SparseArray<View> views;//相似hashMap ,可是更高效强大
private final Context context;
private int position;
private View convertView;
Object associatedObject;//item的数据 item
protected BaseAdapterHelper(Context context, ViewGroup parent, int layoutId, int position) {
this.context = context;
this.position = position;
this.views = new SparseArray<View>();
convertView = LayoutInflater.from(context)
.inflate(layoutId, parent, false);
convertView.setTag(this);
}
// 静态方法。依据listview里getView的參数生成BaseAdapterHelper
public static BaseAdapterHelper get(Context context, View convertView, ViewGroup parent, int layoutId) {
return get(context, convertView, parent, layoutId, -1);
}
static BaseAdapterHelper get(Context context, View convertView, ViewGroup parent, int layoutId, int position) {
if (convertView == null) {
return new BaseAdapterHelper(context, parent, layoutId, position);
}
BaseAdapterHelper existingHelper = (BaseAdapterHelper) convertView.getTag();
existingHelper.position = position;
return existingHelper;
}
// 依据id得到控件
public <T extends View> T getView(int viewId) {
return retrieveView(viewId);
}
@SuppressWarnings("unchecked")
protected <T extends View> T retrieveView(int viewId) {
View view = views.get(viewId);
if (view == null) {
view = convertView.findViewById(viewId);
views.put(viewId, view);
}
return (T) view;
}
// textview 设置文字
public BaseAdapterHelper setText(int viewId, String value) {
TextView view = retrieveView(viewId);
view.setText(value);
return this;
}
// 设置图片
public BaseAdapterHelper setImageResource(int viewId, int imageResId) {
ImageView view = retrieveView(viewId);
view.setImageResource(imageResId);
return this;
}
// 设置颜色
public BaseAdapterHelper setBackgroundColor(int viewId, int color) {
View view = retrieveView(viewId);
view.setBackgroundColor(color);
return this;
}
// 设置背景图片
public BaseAdapterHelper setBackgroundRes(int viewId, int backgroundRes) {
View view = retrieveView(viewId);
view.setBackgroundResource(backgroundRes);
return this;
}
public BaseAdapterHelper setTextColor(int viewId, int textColor) {
TextView view = retrieveView(viewId);
view.setTextColor(textColor);
return this;
}
public BaseAdapterHelper setTextColorRes(int viewId, int textColorRes) {
TextView view = retrieveView(viewId);
view.setTextColor(context.getResources().getColor(textColorRes));
return this;
}
public BaseAdapterHelper setImageDrawable(int viewId, Drawable drawable) {
ImageView view = retrieveView(viewId);
view.setImageDrawable(drawable);
return this;
}
// 设置图片url 。异步下载图片
public BaseAdapterHelper setImageUrl(int viewId, String imageUrl) {
ImageView view = retrieveView(viewId);
Picasso.with(context).load(imageUrl).into(view);
return this;
}
// requestBuilder是Picasso request builder ,异步载入图片
public BaseAdapterHelper setImageBuilder(int viewId, RequestCreator requestBuilder) {
ImageView view = retrieveView(viewId);
requestBuilder.into(view);
return this;
}
public BaseAdapterHelper setImageBitmap(int viewId, Bitmap bitmap) {
ImageView view = retrieveView(viewId);
view.setImageBitmap(bitmap);
return this;
}
// 设置图片的透明度
public BaseAdapterHelper setAlpha(int viewId, float value) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
retrieveView(viewId).setAlpha(value);
} else {
// Pre-honeycomb hack to set Alpha value
AlphaAnimation alpha = new AlphaAnimation(value, value);
alpha.setDuration(0);
alpha.setFillAfter(true);
retrieveView(viewId).startAnimation(alpha);
}
return this;
}
public BaseAdapterHelper setVisible(int viewId, boolean visible) {
View view = retrieveView(viewId);
view.setVisibility(visible ?
View.VISIBLE : View.GONE);
return this;
}
//加入 addLinks
public BaseAdapterHelper linkify(int viewId) {
TextView view = retrieveView(viewId);
Linkify.addLinks(view, Linkify.ALL);
return this;
}
// 文本框字体
public BaseAdapterHelper setTypeface(int viewId, Typeface typeface) {
TextView view = retrieveView(viewId);
view.setTypeface(typeface);
view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
return this;
}
public BaseAdapterHelper setTypeface(Typeface typeface, int... viewIds) {
for (int viewId : viewIds) {
TextView view = retrieveView(viewId);
view.setTypeface(typeface);
view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
return this;
}
// 设置进度条
public BaseAdapterHelper setProgress(int viewId, int progress) {
ProgressBar view = retrieveView(viewId);
view.setProgress(progress);
return this;
}
public BaseAdapterHelper setProgress(int viewId, int progress, int max) {
ProgressBar view = retrieveView(viewId);
view.setMax(max);
view.setProgress(progress);
return this;
}
public BaseAdapterHelper setMax(int viewId, int max) {
ProgressBar view = retrieveView(viewId);
view.setMax(max);
return this;
}
public BaseAdapterHelper setRating(int viewId, float rating) {
RatingBar view = retrieveView(viewId);
view.setRating(rating);
return this;
}
public BaseAdapterHelper setRating(int viewId, float rating, int max) {
RatingBar view = retrieveView(viewId);
view.setMax(max);
view.setRating(rating);
return this;
}
// 设置控件的点击事件
public BaseAdapterHelper setOnClickListener(int viewId, View.OnClickListener listener) {
View view = retrieveView(viewId);
view.setOnClickListener(listener);
return this;
}
// 设置控件的onTouch事件
public BaseAdapterHelper setOnTouchListener(int viewId, View.OnTouchListener listener) {
View view = retrieveView(viewId);
view.setOnTouchListener(listener);
return this;
}
public BaseAdapterHelper setOnLongClickListener(int viewId, View.OnLongClickListener listener) {
View view = retrieveView(viewId);
view.setOnLongClickListener(listener);
return this;
}
// 设置控件的tag
public BaseAdapterHelper setTag(int viewId, Object tag) {
View view = retrieveView(viewId);
view.setTag(tag);
return this;
}
public BaseAdapterHelper setTag(int viewId, int key, Object tag) {
View view = retrieveView(viewId);
view.setTag(key, tag);
return this;
}
// 设置选中状态
public BaseAdapterHelper setChecked(int viewId, boolean checked) {
Checkable view = (Checkable) retrieveView(viewId);
view.setChecked(checked);
return this;
}
// 设置adapter
public BaseAdapterHelper setAdapter(int viewId, Adapter adapter) {
AdapterView view = retrieveView(viewId);
view.setAdapter(adapter);
return this;
}
public View getView() {
return convertView;
}
// 得到item的position,假设是-1,则异常
public int getPosition() {
if (position == -1)
throw new IllegalStateException("Use BaseAdapterHelper constructor " +
"with position if you need to retrieve the position.");
return position;
}
public Object getAssociatedObject() {
return associatedObject;
}
/** Should be called during convert */
public void setAssociatedObject(Object associatedObject) {
this.associatedObject = associatedObject;
}
}
构造函数是一些初始化,convertView的载入。views的初始化。
看这个静态方法,static BaseAdapterHelper get(Context context, View convertView, ViewGroup parent, int layoutId, int position)
,能够通过类名.的方式生成这个类的实例。传入的convertView是listview的getView方法里的。layoutId即为item的布局文件id。
protected <T extends View> T retrieveView(int viewId)
这种方法替代了holderview的作用。
后面的方法都是设置控件的属性或者事件等等,注意associatedObject这个属性是item的data,所以是Object类型。
再看看核心的BaseQuickAdapter。
代码:
package com.joanzapata.android;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseQuickAdapter<T, H extends BaseAdapterHelper> extends BaseAdapter {
protected static final String TAG = BaseQuickAdapter.class.getSimpleName();
protected final Context context;
protected final int layoutResId;
protected final List<T> data;
protected boolean displayIndeterminateProgress = false;
public BaseQuickAdapter(Context context, int layoutResId) {
this(context, layoutResId, null);
}
//依据layoutId和data初始化
public BaseQuickAdapter(Context context, int layoutResId, List<T> data) {
this.data = data == null ? new ArrayList<T>() : new ArrayList<T>(data);
this.context = context;
this.layoutResId = layoutResId;
}
//假设Progress显示则加1
@Override
public int getCount() {
int extra = displayIndeterminateProgress ?
1 : 0;
return data.size() + extra;
}
@Override
public T getItem(int position) {
if (position >= data.size()) return null;
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
// item type的数量,两种,一种是item,都是同样的,还有一种是Progress
@Override
public int getViewTypeCount() {
return 2;
}
// 当position超过data数量时,载入progress,是还有一种布局
@Override
public int getItemViewType(int position) {
return position >= data.size() ?
1 : 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == 0) {//普通布局
final H helper = getAdapterHelper(position, convertView, parent);//getAdapterHelper()是一个抽象方法,子类实现,须要提供的參数是layoutID,也就是item的布局
T item = getItem(position);
helper.setAssociatedObject(item);
convert(helper, item);//convert须要之类实现。功能逻辑
return helper.getView();
}
return createIndeterminateProgressView(convertView, parent);//载入progress布局
}
private View createIndeterminateProgressView(View convertView, ViewGroup parent) {
if (convertView == null) {
FrameLayout container = new FrameLayout(context);
container.setForegroundGravity(Gravity.CENTER);
ProgressBar progress = new ProgressBar(context);
container.addView(progress);
convertView = container;
}
return convertView;
}
@Override
public boolean isEnabled(int position) {
return position < data.size();
}
public void add(T elem) {
data.add(elem);
notifyDataSetChanged();
}
public void addAll(List<T> elem) {
data.addAll(elem);
notifyDataSetChanged();
}
public void set(T oldElem, T newElem) {
set(data.indexOf(oldElem), newElem);
}
public void set(int index, T elem) {
data.set(index, elem);
notifyDataSetChanged();
}
public void remove(T elem) {
data.remove(elem);
notifyDataSetChanged();
}
public void remove(int index) {
data.remove(index);
notifyDataSetChanged();
}
public void replaceAll(List<T> elem) {
data.clear();
data.addAll(elem);
notifyDataSetChanged();
}
public boolean contains(T elem) {
return data.contains(elem);
}
/** Clear data list */
public void clear() {
data.clear();
notifyDataSetChanged();
}
public void showIndeterminateProgress(boolean display) {
if (display == displayIndeterminateProgress) return;
displayIndeterminateProgress = display;
notifyDataSetChanged();
}
/**
* Implement this method and use the helper to adapt the view to the given item.
* @param helper A fully initialized helper.
* @param item The item that needs to be displayed.
*/
protected abstract void convert(H helper, T item);
/**
* You can override this method to use a custom BaseAdapterHelper in order to fit your needs
* @param position The position of the item within the adapter's data set of the item whose view we want.
* @param convertView The old view to reuse, if possible. Note: You should check that this view
* is non-null and of an appropriate type before using. If it is not possible to convert
* this view to display the correct data, this method can create a new view.
* Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}).
* @param parent The parent that this view will eventually be attached to
* @return An instance of BaseAdapterHelper
*/
protected abstract H getAdapterHelper(int position, View convertView, ViewGroup parent);
}
这个类继承了BaseAdapter,是抽象类,抽象方法为protected abstract void convert(H helper, T item);
和protected abstract H getAdapterHelper(int position, View convertView, ViewGroup parent);
供子类实现,convert是用户须要实现的功能逻辑,getAdapterHelper须要用户提供item的layoutId。
这个类设计的是包括两种布局,一种是用户自己定义的item布局,还有一种是Progress的布局,所以在getCount()返回的是data.size()+1,getViewTypeCount()返回2,区分这两种用getItemViewType()。
看最重要的getView()方法,首先依据getItemViewType()推断类型,为0 就是item布局,通过调用子类的getAdapterHelper()方法得到对应的AdapterHelper进行设置。为1就是Progress。通过new了一个FrameLayout布局实现。在item生成过程中,convert()是最重要的。对于实际的开发,一般用于设置item图片载入、文本框设置文本等等相似逻辑。
大概重要的都说了,代码凝视也有。在上面第一个提到的文章里也说了,这个项目不支持item有多个布局,事实上我们能够改动,那篇文章里也有,详细的就是添加一个布局数组,在getView()方法中加以推断,比方聊天界面,有发送方和接收方。布局是左右相反的,一个是靠左。还有一个靠右,在消息类里肯定有这个属性,是否是自己发送。用这个项目其中来。就是重写getItemViewType(),在getView()中推断和载入。
努力学习和运用开源项目,了解后面的原理和流程,对自己思路和能力都有非常大提高,还要继续学习。
。
对base-adapter-helper的简单分析的更多相关文章
- PC-lint集成于SourceInsight 范例以及简单分析;提高代码的健壮性;
写代码之际突然想起了pc-lint这个"古董级"的代码静态分析工具; 下午机房的服务器歇菜了,没法调试游戏,刚好抽出时间来研究一下pc-lint集成在SourceInsight ...
- FFmpeg源码简单分析:libswscale的sws_scale()
===================================================== FFmpeg的库函数源码分析文章列表: [架构图] FFmpeg源码结构图 - 解码 FFm ...
- x264源代码简单分析:宏块分析(Analysis)部分-帧内宏块(Intra)
===================================================== H.264源代码分析文章列表: [编码 - x264] x264源代码简单分析:概述 x26 ...
- FFmpeg源代码简单分析:libavdevice的gdigrab
===================================================== FFmpeg的库函数源代码分析文章列表: [架构图] FFmpeg源代码结构图 - 解码 F ...
- FFmpeg源代码简单分析:configure
===================================================== FFmpeg的库函数源代码分析文章列表: [架构图] FFmpeg源代码结构图 - 解码 F ...
- FFmpeg源代码简单分析:libswscale的sws_scale()
===================================================== FFmpeg的库函数源代码分析文章列表: [架构图] FFmpeg源代码结构图 - 解码 F ...
- ThinkPHP5代码执行的简单分析
漏洞影响版本: ThinkPHP 5.0.5-5.0.22 ThinkPHP 5.1.0-5.1.30 漏洞复现: 一.mac的debug环境搭建. 一键化环境搭建工具: mamp pro ,调试工具 ...
- Django-session中间件源码简单分析
Django-session中间件源码简单分析 settings里有关中间件的配置 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddlew ...
- opencart 单入口文件简单分析
opencart 单入口文件简单分析 opencart是基于mvcl的商城系统,据说是一个外国有人单独开发.比较牛叉.但是又不大符合国人习惯,目前国内opencart社区也是不少. 简单分析了下单 ...
- 简单分析JavaScript中的面向对象
初学JavaScript的时候有人会认为JavaScript不是一门面向对象的语言,因为JS是没有类的概念的,但是这并不代表JavaScript没有对象的存在,而且JavaScript也提供了其它的方 ...
随机推荐
- 在OSX狮子(Lion)上安装MYSQL(Install MySQL on Mac OSX)
这篇文章简述了在Mac OSX狮子(Lion)上安装MySQL Community Server最新版本v10.6.7的过程. MySQL是最流行的开源数据库管理系统.首先,从MySQL的下载页面上下 ...
- 统计难题(trie树)
统计难题 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)Total Submi ...
- [置顶] 如何在Windows 7 64位安装Python,并使用Matplotlib绘图
1. 安装Python 我使用的是Windows 7 64 bit,所以我从Python官网下载python-2.7.5.amd64.msi,安装步骤如下: 1) 安装windo ...
- 【剑指offer】面试题43:n个骰子的点数
第一种思路是,每一个骰子的点数从最小到最大,如果为1-6,那么全部的骰子从最小1開始,我们如果一种从左向右的排列,右边的最低,索引从最低開始,推断和的情况. def setTo1(dices, sta ...
- 杭电ACM 汉字统计
汉字统计 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submi ...
- beta分布
http://blog.csdn.net/sweetrryy/article/details/6436358
- qemu核心机制分析-协程coroutine
关于协程coroutine前面的文章已经介绍过了,本文总结对qemu中coroutine机制的分析,qemu 协程coroutine基于:setcontext函数族以及函数间跳转函数siglongjm ...
- 【转】Plotting texts as graphs with R and igraph
原文转自:http://blog.ynada.com/303 I’ve plotted several word association graphs for this New York Times ...
- Identity-修改Error错误提示为中文
第一步:重写IdentityErrorDescriber public class CustomIdentityErrorDescriber : IdentityErrorDescriber ...
- thinkphp 常用的查询
php 常用的数据库查询方式: //根据where 条件查询,使用select()方法 访问:http://localhost/thinkphp2/index.php/Machine/search_i ...