• 自己实现CursorAdapter


    没什么好说的,注意bindView和newView就行。

     1 public class MySimpleCursorAdapter extends CursorAdapter {
     2     private LayoutInflater mInflater;
     3 
     4     public MySimpleCursorAdapter(Context context, Cursor c) {
     5         super(context, c, false);
     6         mInflater = LayoutInflater.from(context);
     7     }
     8 
     9     @Override
    10     public View newView(Context context, Cursor cursor, ViewGroup parent) {
    11         return mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
    12     }
    13 
    14     @Override
    15     public void bindView(View view, Context context, Cursor cursor) {
    16         TextView text = (TextView)view.findViewById(android.R.id.text1);
    17         text.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
    18     }
    19 }

    主Activity

    1         Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,  
    2                 null, null, null);
    3         MySimpleCursorAdapter cursorAdapter = new MySimpleCursorAdapter(this, cursor);
    4         listview.setAdapter(cursorAdapter);

    好了,就这么简单。

    CursorAdapter也是BaseAdapter的一个子类,重写getView方法时用到了bindView和newView

     1     public View getView(int position, View convertView, ViewGroup parent) {
     2         if (!mDataValid) {
     3             throw new IllegalStateException("this should only be called when the cursor is valid");
     4         }
     5         if (!mCursor.moveToPosition(position)) {
     6             throw new IllegalStateException("couldn't move cursor to position " + position);
     7         }
     8         View v;
     9         if (convertView == null) {
    10             v = newView(mContext, mCursor, parent);
    11         } else {
    12             v = convertView;
    13         }
    14         bindView(v, mContext, mCursor);
    15         return v;
    16     }

    第一屏显示完后,再去滑动listview,系统会直接调用bindView,不会再去new了。

  • 相关阅读:
    用C++读写EXCEL文件的几种方式比较
    20个值得收藏的网页设计开放课件
    char* 应用, 去除字符串内多余空格, 用算法而非库函数
    东拉西扯:王建硕主义
    Lisp 的本质(The Nature of Lisp)
    web前端:html
    [原译]理解并实现原型模式实现ICloneable接口.理解深浅拷贝
    [原译]理解并实现装饰器模式
    3分钟理解Lambda表达式
    [原译]实现IEnumerable接口&理解yield关键字
  • 原文地址:https://www.cnblogs.com/feiyunruyue/p/3137974.html
Copyright © 2020-2023  润新知