打造通用ListView、GridView

参考转载自http://blog.csdn.net/lmj623565791/article/details/38902805 ,本文出自【张鸿洋的博客】

 

一、一般ListView需要

1.适配器(一般继承BaseAdapter,创建构造函数,重写几个方法,再加上setData()方法当数据源改变时刷新数据)

2.ViewHolder(避免重复创建控件提高效率)

public class XAdapeter extends BaseAdapter{

    private Context mContext;
    private List<String> mData;

    public XAdapeter(Context context,List<String> data){
        this.mContext=context;
        this.mData=data;
    }

    @Override
    public int getCount() {
        return mData==null?0:mData.size();
    }

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

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

    public void setData(List<String> data){
        mData=data;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder=null;
        if (convertView==null){
            convertView= LayoutInflater.from(mContext).inflate(R.layout.item_project,parent,false);
            viewHolder=new ViewHolder();
            viewHolder.text= (TextView) convertView.findViewById(R.id.tv_item);
            viewHolder.icon= (ImageView)convertView.findViewById(R.id.iv_icon);
            convertView.setTag(viewHolder);
        }else {
            viewHolder=(ViewHolder) convertView.getTag();
        }
        viewHolder.text.setText(mData.get(position).toString());
        return convertView;
    }

    public final class ViewHolder{
        private TextView text;
        private ImageView icon;

    }
}

 

3.单元布局文件

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/iv_icon"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/dp_40"
            android:src="@drawable/icon_location_picture"
            android:layout_marginTop="@dimen/dp_10"
            android:layout_marginLeft="@dimen/dp_10"
            android:layout_marginBottom="@dimen/dp_5"
            />

        <TextView
            android:id="@+id/tv_item"
            android:layout_weight="5"
            android:text="0000000000000000"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:textSize="@dimen/sp_15"/>
    </LinearLayout>
</RelativeLayout>

4.Activity实现ListView

public class FirstActivity extends BaseActivity {

    //下拉上拉刷新ListView
    //private PullToRefreshListView; com.handmark.pulltorefresh.library
    private List<String> data;
    private ListView listView;
    private XAdapeter adapeter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        data=new ArrayList<>();
        for (int i=0;i<10;i++){
            data.add("第"+i+"个");
        }
        //绑定个ListView控件
        listView=(ListView)findViewById(R.id.search_content_show_list);
        //新建适配器
        adapeter=new XAdapeter(this,data);
        
        //下拉上拉刷新ListView配置
//        listView.getRefreshableView().setHeaderDividersEnabled(false);
//        listView.setMode(PullToRefreshBase.Mode.BOTH);
//        listView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载更多");
//        listView.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新");
        
        //添加适配器
        listView.setAdapter(adapeter);
        //重新加载数据
        data.clear();
        for (int i=10;i<20;i++){
            data.add("第"+i+"个");
        }
        adapeter.setData(data);

    }

}

二、我们可以从ViewHolder、Adapter几个重复代码多的地方下手进行优化,打造通用的代码

1.通用ViewHolder

//通用ViewHolder类
public  class BaseViewHolder {

    private final SparseArray<View> mViews;
    private View mConvertView;

    public BaseViewHolder(Context context, ViewGroup parent, int layoutId,
                       int position)
    {
        this.mViews = new SparseArray<View>();
        mConvertView = LayoutInflater.from(context).inflate(layoutId, parent,
                false);
        //setTag
        mConvertView.setTag(this);
    }

    /**
     * 拿到一个ViewHolder对象
     * @param context
     * @param convertView
     * @param parent
     * @param layoutId
     * @param position
     * @return
     */
    public static BaseViewHolder get(Context context, View convertView,
                                 ViewGroup parent, int layoutId, int position)
    {

        if (convertView == null)
        {
            return new BaseViewHolder(context, parent, layoutId, position);
        }
        return (BaseViewHolder) convertView.getTag();
    }


    /**
     * 通过控件的Id获取对于的控件,如果没有则加入views
     * @param viewId
     * @return
     */
    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;
    }


    /**
     * 为TextView设置字符串
     *
     * @param viewId
     * @param text
     * @return
     */
    public BaseViewHolder setText(int viewId, String text)
    {
        TextView view = getView(viewId);
        view.setText(text);
        return this;
    }

    /**
     * 为ImageView设置图片
     *
     * @param viewId
     * @param drawableId
     * @return
     */
    public BaseViewHolder setImageResource(int viewId, int drawableId)
    {
        ImageView view = getView(viewId);
        view.setImageResource(drawableId);

        return this;
    }

    /**
     * 为ImageView设置图片
     *
     * @param viewId
     * @param bm
     * @return
     */
    public BaseViewHolder setImageBitmap(int viewId, Bitmap bm)
    {
        ImageView view = getView(viewId);
        view.setImageBitmap(bm);
        return this;
    }

//    /**
//     * 为ImageView设置图片
//     *
//     * @param viewId
//     * @param url
//     * @return
//     */
//    public BaseViewHolder setImageByUrl(int viewId, String url)
//    {
//        ImageLoader.getInstance(3, Type.LIFO).loadImage(url,
//                (ImageView) getView(viewId));
//        return this;
//    }

    public View getConvertView()
    {
        return mConvertView;
    }
}

2.通用Adapter

//CommonAdapter  使用了通用ViewHolder  
public abstract class CommonAdapter<T> extends BaseAdapter{

    protected LayoutInflater mInflater;
    protected Context mContext;
    protected List<T> mDatas;
    protected final int mItemLayoutId;

    public CommonAdapter(Context context,List<T> data,int resId){
        mContext=context;
        mInflater=LayoutInflater.from(mContext);
        mItemLayoutId=resId;
        if (mDatas==null){
            mDatas=new ArrayList<>();
        }else {
            mDatas=data;
        }
    }
    @Override
    public int getCount() {
        return mDatas==null?0:mDatas.size();
    }

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

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

    public void setData(List<T> data){
        this.mDatas=data;
        notifyDataSetChanged();
    };

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

        BaseViewHolder holder=BaseViewHolder.get(mContext,convertView,parent,mItemLayoutId,position);
        convert(holder,getItem(position));
        return holder.getConvertView();
    }
    public abstract void convert(BaseViewHolder viewHolder,T item);
}

 

3.Activity中使用

 

//继承通用适配器类使用   activity中使用方法同上
public class ProjectListAdapter extends CommonAdapter<HashMap<String,Object>>{
    private static final String TAG = "ProjectListAdapter";
    private Context context;
    private ArrayList<HashMap<String,Object>> data;

    public ProjectListAdapter(Context context,ArrayList<HashMap<String,Object>> data,int resId){
        super(context,data,resId);
        this.context=context;
        if (data==null){
            this.data=new ArrayList<>();
        }else {
            this.data=data;
        }

    }


    @Override
    public void convert(BaseViewHolder viewHolder, final HashMap item) {

        TextView tv=viewHolder.getView(R.id.tv_item);
        ImageView iv=viewHolder.getView(R.id.iv_icon);
        tv.setText((item).get("xmMc").toString());
        viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(context, DetailActivity.class);
                MyApplication.getApp().getAppConfig().setXmlGuid((String)item.get("xmguid"));
                Toast.makeText(context,"前往详细界面",Toast.LENGTH_SHORT);
                Log.d(TAG, "onClick: "+"前往详细界面");
                context.startActivity(intent);
            }
        });
    }
    public static class ViewHolder{
        ImageView ivIcon;
        TextView tvItem;
    }
}

 

 

//匿名内部类实现
            adapter= new CommonAdapter<HashMap<String,Object>>(context,null,R.layout.item_project) {

                @Override
                public void convert(BaseViewHolder viewHolder, final HashMap<String,Object> item) {
                    TextView tv=viewHolder.getView(R.id.tv_item);
                    ImageView iv=viewHolder.getView(R.id.iv_icon);
                    tv.setText((item).get("xmMc").toString());
                    viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent=new Intent(context, DetailActivity.class);
                            MyApplication.getApp().getAppConfig().setXmlGuid((String)item.get("xmguid"));
                            Toast.makeText(context,"前往详细界面",Toast.LENGTH_SHORT);
                            Log.d(TAG, "onClick: "+"前往详细界面");
                            context.startActivity(intent);
                        }
                    });
                 }
            };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值