1. Adapter的关系图
2. CursorAdapter构造函数
public CursorAdapter (Context context, Cursor c)
public CursorAdapter (Context context, Cursor c, boolean autoRequery)
public CursorAdapter (Context context, Cursor c, int flags)
Flags used to determine the behavior of the adapter; may be any combination ofFLAG_AUTO_REQUERY
and
FLAG_REGISTER_CONTENT_OBSERVER
.
3. newView 与 bindView
public abstract void bindView (View view, Context context, Cursor cursor)
Bind an existing view to the data pointed to by cursor //重用一个已有的view,使其显示当前cursor所指向的数据。
参数
view | Existing view, returned earlier by newView |
---|---|
context | Interface to application's global information |
cursor | The cursor from which to get the data. The cursor is already moved to the correct position. |
public abstract View newView (Context context, Cursor cursor, ViewGroup parent)
Makes a new view to hold the data pointed to by cursor. //新建一个视图来保存cursor指向的数据
参数
context | Interface to application's global information |
---|---|
cursor | The cursor from which to get the data. The cursor is already moved to the correct position. |
parent | The parent to which the new view is attached to |
- the newly created view.
4.例子:
public MyCursorAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from (parent.getContext())
.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.textView = (TextView) view.findViewById(R.id.name);
viewHolder.textView.setText(cursor.getString(cursor
.getColumnIndex(Contacts.DISPLAY_NAME)));
view.setTag(viewHolder);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
final ViewHolder viewHolder = (ViewHolder)view.getTag();
viewHolder.textView.setText(cursor.getString(cursor
.getColumnIndex(Contacts.DISPLAY_NAME)));
viewHolder.textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(),viewHolder.textView.getText().toString(),Toast.LENGTH_SHORT).show();
}
});
}
private class ViewHolder {
public TextView textView;
}
Activity:
private static final String[] PROJECTION = new String[] { Contacts._ID,
Contacts.DISPLAY_NAME };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor cursor = getContentResolver().query(Contacts.CONTENT_URI,
PROJECTION, null, null, null);
startManagingCursor(cursor);
setListAdapter(new MyCursorAdapter(getApplicationContext(), cursor,false));
}
5.扩展
}else{
String name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
viewHolder.editeText.setText(name);
}
}