Android开发中经常需要使用Adapter。
传统方法是自定义一个Adapter并继承AndroidSDK内的BaseAdapter,
这种方式代码量大,耦合度高,灵活性差(各种监听事件需要对View单独写,或者自定义一个比较统一的方法);
而ZBLibrary中的BaseViewAdapter不仅预处理了通用方法(getCount,getItem等) 以及 Item复用逻辑,
而且将对Item的处理代码单独写在一个BaseView(提供了大量常用方法)的子类,
所以使用继承BaseViewAdapter的新方式能大幅精简代码,并且带来高灵活性和低耦合度。
比如这个界面
传统方式实现的CommonAdapter代码如下
package com.example.quickadapter; import java.util.ArrayList;
import java.util.List; import zuo.biao.library.ui.WebViewActivity;
import zuo.biao.library.util.ImageLoaderUtil;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView; public class CommonAdapter extends BaseAdapter { private Activity context;
private List<User> list;
private LayoutInflater inflater;
public CommonAdapter(Activity context, List<User> list) {
this.context = context;
this.list = new ArrayList<>(list);
this.inflater = context.getLayoutInflater();
} @Override
public int getCount() {
return list.size();
} @Override
public User getItem(int position) {
return list.get(position);
} @Override
public long getItemId(int position) {
return position;
} public synchronized void refresh(List<User> list) {
if (list != null && list.size() > 0) {
this.list = new ArrayList<>(list);
}
notifyDataSetChanged();
} @Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = convertView == null ? null : (ViewHolder) convertView.getTag();
if (holder == null) {
convertView = inflater.inflate(R.layout.user_item, parent, false);
holder = new ViewHolder(); holder.ivUserItemHead = (ImageView) convertView.findViewById(R.id.ivUserItemHead);
holder.ivUserItemStar = (ImageView) convertView.findViewById(R.id.ivUserItemStar); holder.tvUserItemSex = (TextView) convertView.findViewById(R.id.tvUserItemSex); holder.tvUserItemName = (TextView) convertView.findViewById(R.id.tvUserItemName);
holder.tvUserItemId = (TextView) convertView.findViewById(R.id.tvUserItemId);
holder.tvUserItemNumber = (TextView) convertView.findViewById(R.id.tvUserItemNumber); convertView.setTag(holder);
} final User user = getItem(position); ImageLoaderUtil.loadImage(holder.ivUserItemHead, user.getHead(), ImageLoaderUtil.TYPE_OVAL);
holder.ivUserItemStar.setImageResource(user.getStarred() ? R.drawable.star_light : R.drawable.star); holder.tvUserItemSex.setBackgroundResource(user.getSex() == User.SEX_FEMAIL ? R.drawable.circle_pink : R.drawable.circle_blue);
holder.tvUserItemSex.setText(user.getSex() == User.SEX_FEMAIL ? "女" : "男");
holder.tvUserItemSex.setTextColor(context.getResources().getColor(user.getSex() == User.SEX_FEMAIL ? R.color.pink : R.color.blue)); holder.tvUserItemName.setText("" + user.getName());
holder.tvUserItemId.setText("ID:" + user.getId());
holder.tvUserItemNumber.setText("Phone:" + user.getPhone()); holder.ivUserItemHead.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
context.startActivity(WebViewActivity.createIntent(context, user.getName(), user.getHead()));
}
}); holder.ivUserItemStar.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
user.setStarred(! user.getStarred());
list.set(position, user);
refresh(null);
}
}); holder.tvUserItemSex.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
user.setSex(user.getSex() == User.SEX_FEMAIL ? User.SEX_MAIL : User.SEX_FEMAIL);
list.set(position, user);
refresh(null);
}
}); return convertView;
} class ViewHolder {
public ImageView ivUserItemHead;
public ImageView ivUserItemStar; public TextView tvUserItemSex; public TextView tvUserItemName;
public TextView tvUserItemId;
public TextView tvUserItemNumber;
}
}
继承BaseViewAdapter的新方式实现的QuickAdapter代码如下
package com.example.quickadapter; import java.util.List; import zuo.biao.library.base.BaseView;
import zuo.biao.library.base.BaseViewAdapter;
import zuo.biao.library.ui.WebViewActivity;
import zuo.biao.library.util.ImageLoaderUtil;
import zuo.biao.library.util.StringUtil;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView; import com.example.quickadapter.QuickAdapter.UserView; public class QuickAdapter extends BaseViewAdapter<User, UserView> { public QuickAdapter(Activity context, List<User> list) {
super(context, list);
} @Override
public UserView createView(int position, View convertView, ViewGroup parent) {
return new UserView(context, resources);
} public class UserView extends BaseView<User> implements OnClickListener {
public UserView(Activity context, Resources resources) {
super(context, resources);
} public ImageView ivUserViewHead;
public ImageView ivUserViewStar; public TextView tvUserViewSex; public TextView tvUserViewName;
public TextView tvUserViewId;
public TextView tvUserViewNumber;
@SuppressLint("InflateParams")
@Override
public View createView(LayoutInflater inflater) {
convertView = inflater.inflate(R.layout.user_view, null); ivUserViewHead = findViewById(R.id.ivUserViewHead, this);
ivUserViewStar = findViewById(R.id.ivUserViewStar, this); tvUserViewSex = findViewById(R.id.tvUserViewSex, this); tvUserViewName = findViewById(R.id.tvUserViewName);
tvUserViewId = findViewById(R.id.tvUserViewId);
tvUserViewNumber = findViewById(R.id.tvUserViewNumber); return convertView;
} @Override
public void setView(User data){
if (data == null) {
return;
}
this.data = data; ImageLoaderUtil.loadImage(ivUserViewHead, data.getHead(), ImageLoaderUtil.TYPE_OVAL);
ivUserViewStar.setImageResource(data.getStarred() ? R.drawable.star_light : R.drawable.star); tvUserViewSex.setBackgroundResource(data.getSex() == User.SEX_FEMAIL ? R.drawable.circle_pink : R.drawable.circle_blue);
tvUserViewSex.setText(data.getSex() == User.SEX_FEMAIL ? "女" : "男");
tvUserViewSex.setTextColor(getColor(data.getSex() == User.SEX_FEMAIL ? R.color.pink : R.color.blue)); tvUserViewName.setText(StringUtil.getTrimedString(data.getName()));
tvUserViewId.setText("ID:" + data.getId());
tvUserViewNumber.setText("Phone:" + StringUtil.getNoBlankString(data.getPhone()));
} @Override
public void onClick(View v) {
if (data == null) {
return;
}
switch (v.getId()) {
case R.id.ivUserViewHead:
toActivity(WebViewActivity.createIntent(context, data.getName(), data.getHead()));
break;
case R.id.ivUserViewStar:
data.setStarred(! data.getStarred());
setView(data);
break;
case R.id.tvUserViewSex:
data.setSex(data.getSex() == User.SEX_FEMAIL ? User.SEX_MAIL : User.SEX_FEMAIL);
setView(data);
break;
default:
break;
}
}
}
}
看下ZBLibrary中的BaseView,里面有大量常用的 且 AndroidSDK内的BaseAdapter没有提供的 方法。
package zuo.biao.library.base; import zuo.biao.library.util.CommonUtil;
import zuo.biao.library.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener; /**基础自定义View
* @author Lemon
* @param <T> 数据模型(model/JavaBean)类
* @see #onDestroy
* @use extends BaseView<T>, 具体参考.DemoView
*/
public abstract class BaseView<T> {
private static final String TAG = "BaseView"; /**
* 传入的Activity,可在子类直接使用
*/
protected Activity context;
protected Resources resources;
public BaseView(Activity context, Resources resources) {
this.context = context;
this.resources = resources == null ? context.getResources() : resources;
} /**数据改变回调接口
* (Object) getData() - 改变的数据
*/
public interface OnDataChangedListener {
void onDataChanged();
} public OnDataChangedListener onDataChangedListener;//数据改变回调监听类的实例
/**设置数据改变事件监听类
* @param l
*/
public void setOnDataChangedListener(OnDataChangedListener l) {
onDataChangedListener = l;
} public OnTouchListener onTouchListener;//接触View回调监听类的实例
/**设置接触View事件监听类
* @param l
*/
public void setOnTouchListener(OnTouchListener l) {
onTouchListener = l;
} public OnClickListener onClickListener;//点击View回调监听类的实例
/**设置点击View事件监听类
* @param l
*/
public void setOnClickListener(OnClickListener l) {
onClickListener = l;
} public OnLongClickListener onLongClickListener;//长按View回调监听类的实例
/**设置长按View事件监听类
* @param l
*/
public void setOnLongClickListener(OnLongClickListener l) {
onLongClickListener = l;
} /**
* 子类整个视图,可在子类直接使用
* @must createView方法内对其赋值且不能为null
*/
protected View convertView = null; /**通过id查找并获取控件,使用时不需要强转
* @param id
* @return
*/
@SuppressWarnings("unchecked")
public <V extends View> V findViewById(int id) {
return (V) convertView.findViewById(id);
}
/**通过id查找并获取控件,并setOnClickListener
* @param id
* @param l
* @return
*/
public <V extends View> V findViewById(int id, OnClickListener l) {
V v = findViewById(id);
v.setOnClickListener(l);
return v;
}
/**创建一个新的View
* @return
*/
public abstract View createView(@NonNull LayoutInflater inflater); /**获取convertView的宽度
* @warn 只能在createView后使用
* @return
*/
public int getWidth() {
return convertView.getWidth();
}
/**获取convertView的高度
* @warn 只能在createView后使用
* @return
*/
public int getHeight() {
return convertView.getHeight();
} /**
* data在列表中的位置
* @must 只使用setView(int position, T data)方法来设置position,保证position与data对应正确
*/
protected int position = 0;
/**获取data在列表中的位置
*/
public int getPosition() {
return position;
} protected T data = null;
/**获取数据
* @return
*/
public T getData() {
return data;
} /**设置并显示内容
* @warn 只能在createView后使用
* @param position - data在列表中的位置
* @param data - 传入的数据
*/
public void setView(int position, T data) {
this.position = position;
setView(data);
}
/**设置并显示内容
* @warn 只能在createView后使用
* @param data - 传入的数据
*/
public abstract void setView(T data); /**获取可见性
* @warn 只能在createView后使用
* @return 可见性 (View.VISIBLE, View.GONE, View.INVISIBLE);
*/
public int getVisibility() {
return convertView.getVisibility();
}
/**设置可见性
* @warn 只能在createView后使用
* @param visibility - 可见性 (View.VISIBLE, View.GONE, View.INVISIBLE);
*/
public void setVisibility(int visibility) {
convertView.setVisibility(visibility);
} /**设置背景
* @warn 只能在createView后使用
* @param resId
*/
public void setBackground(int resId) {
if (resId > 0 && convertView != null) {
try {
convertView.setBackgroundResource(resId);
} catch (Exception e) {
Log.e(TAG, "setBackground try { convertView.setBackgroundResource(resId);" +
" \n >> } catch (Exception e) { \n" + e.getMessage());
}
}
} //resources方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
public String getString(int id) {
return resources.getString(id);
}
public int getColor(int id) {
return resources.getColor(id);
}
public Drawable getDrawable(int id) {
return resources.getDrawable(id);
}
public float getDimension(int id) {
return resources.getDimension(id);
}
//resources方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //show short toast 方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**快捷显示short toast方法,需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
* @param stringResId
*/
public void showShortToast(int stringResId) {
CommonUtil.showShortToast(context, stringResId);
}
/**快捷显示short toast方法,需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
* @param string
*/
public void showShortToast(String string) {
CommonUtil.showShortToast(context, string);
}
//show short toast 方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //启动新Activity方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /**打开新的Activity,向左滑入效果
* @param intent
*/
public void toActivity(final Intent intent) {
CommonUtil.toActivity(context, intent);
}
/**打开新的Activity
* @param intent
* @param showAnimation
*/
public void toActivity(final Intent intent, final boolean showAnimation) {
CommonUtil.toActivity(context, intent, showAnimation);
}
/**打开新的Activity,向左滑入效果
* @param intent
* @param requestCode
*/
public void toActivity(final Intent intent, final int requestCode) {
CommonUtil.toActivity(context, intent, requestCode);
}
/**打开新的Activity
* @param intent
* @param requestCode
* @param showAnimation
*/
public void toActivity(final Intent intent, final int requestCode, final boolean showAnimation) {
CommonUtil.toActivity(context, intent, requestCode, showAnimation);
}
//启动新Activity方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /**销毁并回收内存,建议在对应的View占用大量内存时使用
* @warn 只能在UI线程中调用
*/
public void onDestroy() {
if (convertView != null) {
try {
convertView.destroyDrawingCache();
} catch (Exception e) {
Log.w(TAG, "onDestroy try { convertView.destroyDrawingCache();" +
" >> } catch (Exception e) {\n" + e.getMessage());
}
convertView = null;
} onDataChangedListener = null;
onTouchListener = null;
onClickListener = null;
onLongClickListener = null; data = null;
position = 0; context = null;
} }
本示例工程QuickAdapter
下载地址
http://files.cnblogs.com/files/tommylemon/QuickAdapter.zip
下载试用
用到的开源库ZBLibrary(欢迎Star,欢迎Fork)
下载地址
https://github.com/TommyLemon/Android-ZBLibrary
下载试用