自己实现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了。

原文地址:https://www.cnblogs.com/feiyunruyue/p/3137974.html