ViewHolder封装*
package com.pcf.listview.bean;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by Administrator on 2016/10/29.
*/
public class ViewHolder {
private SparseArray mViews;//存储view,效率比Map高
private int mPosition;
private View mConvertView;
public ViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
this.mPosition = position;
this.mViews = new SparseArray<View>();
mConvertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
mConvertView.setTag(this);
}
public static ViewHolder get(Context context, View convertView, ViewGroup parent, int layoutId, int position) {
if (convertView == null) {
return new ViewHolder(context, parent, layoutId, position);
} else {
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
viewHolder.mPosition = position;//更新position
return viewHolder;
}
}
public <T extends View> T getView(int viewId) {
View view = mViews.get(viewId);
if (view == null) {
view = mConvertView.findViewById(viewId);
mViews.put(viewId, view);
}
return (T) view;
}
public View getmConvertView() {
return mConvertView;
}
/**
* 返回position
* @return
*/
public int getPosition() {
return mPosition;
}
/**
* 设置textview的值
*
* @param viewId
* @param text
* @return
*/
public ViewHolder setText(int viewId, String text) {
TextView tv = getView(viewId);
tv.setText(text);
return this;
}
/**
* 设置图片,传入resurceId
* @param viewId
* @param resourceId
* @return
*/
public ViewHolder setImageResource(int viewId, int resourceId) {
ImageView imageView = getView(viewId);
imageView.setImageResource(resourceId);
return this;
}
/**
* 设置图片,传图bitmap
* @param viewId
* @param bitmap
* @return
*/
public ViewHolder setImageBitmap(int viewId, Bitmap bitmap) {
ImageView imageView = getView(viewId);
imageView.setImageBitmap(bitmap);
return this;
}
// public ViewHolder setImageResource(int viewId, String url) {
// ImageView imageView = getView(viewId);
// //Imageloader.getInstance.loadimg(view,url)
// imageView.setImageResource(resourceId);
// return this;
// }
}