看别人的项目,封装4~5层以上,就会有点晕的感觉,封装确实是有很多好处,以后慢慢体会。
以前写listview结合baseAdapter和实体类来展示数据:
现在做一个学习记录,觉得对自己有帮助,好的代码能提高自己的工作效率,同时也给别人一种良好的赶脚。
先看代码:
- public class BaseObjectListAdapter extends BaseAdapter {
- protected Context mContext;
- protected LayoutInflater mInflater;
- protected List<? extends Entity> mDatas = new ArrayList<Entity>();
- public BaseObjectListAdapter(Context context,List<? extends Entity> datas) {
- mContext = context;
- mInflater = LayoutInflater.from(context);
- if (datas != null) {
- mDatas = datas;
- }
- }
- @Override
- public int getCount() {
- return mDatas.size();
- }
- @Override
- public Object getItem(int position) {
- return mDatas.get(position);
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- return null;
- }
- public List<? extends Entity> getDatas() {
- return mDatas;
- }
- protected void showCustomToast(String text) {
- View toastRoot = LayoutInflater.from(mContext).inflate(
- R.layout.common_toast, null);
- ((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
- Toast toast = new Toast(mContext);
- toast.setGravity(Gravity.CENTER, 0, 0);
- toast.setDuration(Toast.LENGTH_SHORT);
- toast.setView(toastRoot);
- toast.show();
- }
- }
只需要写构造方法和重写getview方法,感觉方便多了,看到这里应该很清楚了,viewholder优化可以自己实现。节省了时间,提高了效率
- public class ChatAdapter extends BaseObjectListAdapter {
- public ChatAdapter(BaseApplication application, Context context,
- List<? extends Entity> datas) {
- super(application, context, datas);
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- Message msg = (Message) getItem(position);
- MessageItem messageItem = MessageItem.getInstance(msg, mContext);
- messageItem.fillContent();
- View view = messageItem.getRootView();
- return view;
- }
- }
- public class Entity {
- // 暂时可以写个空的,可以根据项目需求来定义
- }
这算是个小技巧吧!