ListView之ViewHolder类封装

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;
// }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值