Adapter简化写法以及findViewById()方法的优化

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/pengkv/article/details/44828901


首先写个ViewHolder:

public class ViewHolder {

    private View mConvertView;

    private Activity mActivity;

    private SparseArray<View> mViewArray;   // 包含了View引用的SparseArray


    public ViewHolder(View convertView) {
        this.mConvertView = convertView;
    }

    public ViewHolder(Activity activity) {
        this.mActivity = activity;
    }


    public <T extends View> T get(int viewId) {//通过ViewId得到View

        if (mActivity == null) {// ListAdapter的ViewHolder

            SparseArray<View> viewHolder = (SparseArray<View>) mConvertView.getTag();
            if (viewHolder == null) {
                viewHolder = new SparseArray<View>();
                mConvertView.setTag(viewHolder);
            }
            View childView = viewHolder.get(viewId);
            if (childView == null) {
                childView = mConvertView.findViewById(viewId);
                viewHolder.put(viewId, childView);
            }
            return (T) childView;

        } else { // Activity的ViewHolder

            if (mViewArray == null) {
                mViewArray = new SparseArray<View>();
            }
            View childView = mViewArray.get(viewId);
            if (childView == null) {
                childView = mActivity.findViewById(viewId);
                mViewArray.put(viewId, childView);
            }
            return (T) childView;
        }
    }

    public void setText(int viewId, String text) {// 通过ViewId设置Text
        ((TextView) get(viewId)).setText(text);
    }

    public void setText(int viewId, Spanned text) {// 通过ViewId设置Text
        ((TextView) get(viewId)).setText(text);
    }

    public void setTextColor(int viewId, int color) {//通过ViewId设置TextColor
        ((TextView) get(viewId)).setTextColor(color);
    }

    public void setImageResource(int viewId, int resId) {//通过ViewId设置图片
        ((ImageView) get(viewId)).setImageResource(resId);
    }

    public void setImageBitmap(int viewId, Bitmap bm) {// 通过ViewId设置图片
        ((ImageView) get(viewId)).setImageBitmap(bm);
    }

    public void setImageDrawable(int viewId, Drawable drawable) {//通过ViewId设置图片
        ((ImageView) get(viewId)).setImageDrawable(drawable);
    }

    public void setImageUrl(int id, String url) {//通过ViewId设置网络图片
//        Rosemary.loadImage(url, (ImageView) get(id));
    }

    public void setImageUrl(int id, String url, int resId) {// 通过ViewId设置网络图片
//        Rosemary.loadImage(url, (ImageView) get(id), resId);
    }

    public void setVisibility(int viewId, int visibility) {//通过ViewId设置隐藏和显示
        get(viewId).setVisibility(visibility);
    }

    public void setOnClickListener(int viewId, View.OnClickListener l) {//通过ViewId设置点击监听
        get(viewId).setOnClickListener(l);
    }

}


然后写个BaseActivity:

public class BaseActivity extends ActionBarActivity {

    protected ViewHolder mHolder;

    public <T> T $(int viewID) {
        return (T) mHolder.get(viewID);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApplication.getInstance().addActivity(this);
        mHolder = new ViewHolder(this);
    }

}

封装个简易Adapter:

public abstract class ListAdapter<T>  extends BaseAdapter {

    protected Context mContext;
    protected LayoutInflater mInflater;

    protected List<T> mList;   // 数据集

    protected int mLayoutID;    // 布局资源ID

    protected ListAdapter() {
    }

    public ListAdapter(Context ctx, List<T> list, int layoutID) {
        mContext = ctx;
        mInflater = LayoutInflater.from(ctx);
        mList = list;
        mLayoutID = layoutID;
    }

    @Override
    public int getCount() {
        if (mList != null && mList.size() > 0) return mList.size();

        return 0;
    }

    @Override
    public T getItem(int position) {
        if (mList != null && mList.size() > 0) return mList.get(position);

        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) convertView = mInflater.inflate(mLayoutID, null);

        ViewHolder holder = new ViewHolder(convertView);
        onBind(position, getItem(position), holder);

        return convertView;
    }

    /**
     * 绑定数据
     */
    protected abstract void onBind(int position, T item, ViewHolder holder);

}

使用效果:

public class BlacklistActivity extends VolleyActivity implements IInit, IResponseHandler {

    private ListView mListView;

    private BlacklistViewModel mViewModel = new BlacklistViewModel();
    private ListAdapter<BlacklistViewModel> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blacklist);

        init();
    }

    @Override
    public void init() {
        ActionBarUtil.setup(this, "我的黑名单");

        mListView = $(R.id.lv_blacklist);

        fetchData(FIRST);
    }

    @Override
    public void fetchData(int tag) {
        toggleProgress(true);
        if (tag == FIRST) {
            // 请求黑名单列表
            GetBlackBuyerListParam param = new GetBlackBuyerListParam(mViewModel.getPageIndex(), Data.PAGE_SIZE_LARGE, Data.getUserID());
            UserApi.getBlackBuyerList(this, param, tag);
        } else if (tag == SECOND) {
            // 移出黑名单
            RemoveBlackBuyerParam param = new RemoveBlackBuyerParam(Data.getUserID(), mViewModel.getList().get(mViewModel.getCurrentPosition()).getModel().getBuyerID());
            UserApi.removeBlackBuyer(this, param, tag);
        }
    }

    @Override
    public void updateUI(Object response, int tag) {
        if (response == null) return;

        if (tag == FIRST) {
            mViewModel.inflate(response);
            // 黑名单列表
            if (mAdapter == null) {
                mAdapter = new ListAdapter<BlacklistViewModel>(this, mViewModel.getList(), R.layout.item_blacklist) {
                    @Override
                    protected void onBind(final int position, final BlacklistViewModel item, ViewHolder holder) {
                        holder.setImageUrl(R.id.iv_avatar, item.getModel().getHeadImageUrl(), R.drawable.defaultportrait);
                        holder.setOnClickListener(R.id.iv_avatar, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                IntentUtil.toPersonInfo(BlacklistActivity.this, item.getModel().getBuyerID());
                            }
                        });
                        holder.setText(R.id.tv_name, item.getModel().getBuyerName());
                        holder.setOnClickListener(R.id.btn_remove, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mViewModel.setCurrentPosition(position);
                                new AlertDialog.Builder(BlacklistActivity.this).setMessage(String.format("确定将“%s”从黑名单中移除吗?", item.getModel().getBuyerName())).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        fetchData(SECOND);
                                    }
                                }).setNegativeButton(android.R.string.cancel, null).create().show();
                            }
                        });
                    }
                };
                mListView.setAdapter(mAdapter);
                mListView.setEmptyView(findViewById(R.id.iv_no_data));
            } else {
                mAdapter.notifyDataSetChanged();
            }
        } else if (tag == SECOND) {
            if (((Boolean) response)) {
                ToastUtil.show(this, "移除成功!");
                mViewModel.getList().remove(mViewModel.getCurrentPosition());
                mAdapter.notifyDataSetChanged();
            }
        }
    }

}

总结:

以前要写mListView = (ListView)findViewById(R.id.lv_blacklist);

现在只要写mListView = $(R.id.lv_blacklist);就可以


而且adapter简化成几行代码:

                mAdapter = new ListAdapter<BlacklistViewModel>(this, mViewModel.getList(), R.layout.item_blacklist) {
                    @Override
                    protected void onBind(final int position, final BlacklistViewModel item, ViewHolder holder) {
                        holder.setImageUrl(R.id.iv_avatar, item.getModel().getHeadImageUrl(), R.drawable.defaultportrait);
                        holder.setOnClickListener(R.id.iv_avatar, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                IntentUtil.toPersonInfo(BlacklistActivity.this, item.getModel().getBuyerID());
                            }
                        });
                        holder.setText(R.id.tv_name, item.getModel().getBuyerName());
                        holder.setOnClickListener(R.id.btn_remove, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mViewModel.setCurrentPosition(position);
                                new AlertDialog.Builder(BlacklistActivity.this).setMessage(String.format("确定将“%s”从黑名单中移除吗?", item.getModel().getBuyerName())).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        fetchData(SECOND);
                                    }
                                }).setNegativeButton(android.R.string.cancel, null).create().show();
                            }
                        });
                    }
                };
                mListView.setAdapter(mAdapter);





展开阅读全文

没有更多推荐了,返回首页