还是从原来163博客中粘贴过来的。
CursorAdapter中的filter
2009-11-25 18:52:47| 分类: Android学习随记 | 标签: |字号大中小 订阅
在看Contacts的代码的时候,发现在ContactsListActivity界面,按下a-z,0-9的时候,都会进行相应的匹配,将不符合匹配的联系人项隐藏起来.如图:
刚开始我以为是响应on
分享一下,免得走弯路了
CursorAdapter
/**
* Runs a query with the specified constraint. This query is requested
* by the filter attached to this adapter.
*
* The query is provided by a
* {@link android.widget.FilterQueryProvider}.
* If no provider is specified, the current cursor is not filtered and returned.
*
* After this method returns the resulting cursor is passed to {@link #changeCursor(Cursor)}
* and the previous cursor is closed.
*
* This method is always executed on a background thread, not on the
* application's main thread (or UI thread.)
*
* Contract: when constraint is null or empty, the original results,
* prior to any filtering, must be returned.
*
* @param constraint the constraint with which the query must be filtered
*
* @return a Cursor representing the results of the new query
*
* @see #getFilter()
* @see #getFilterQueryProvider()
* @see #setFilterQueryProvider(android.widget.FilterQueryProvider)
*/
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (mFilterQueryProvider != null) {
return mFilterQueryProvider.runQuery(constraint);// mFilterQueryProvider这个东西是FilterQueryProviderFilterQueryProvider的一个实例。
}
return mCursor;
}
FilterQueryProvider
/**
* This class can be used by external clients of CursorAdapter and
* CursorTreeAdapter to define how the content of the adapter should be
* filtered.
*
* @see #runQuery(CharSequence)
*/
public interface FilterQueryProvider {
/**
* Runs a query with the specified constraint. This query is requested
* by the filter attached to this adapter.
*
* Contract: when constraint is null or empty, the original results,
* prior to any filtering, must be returned.
*
* @param constraint the constraint with which the query must
* be filtered
*
* @return a Cursor representing the results of the new query
*/
Cursor runQuery(CharSequence constraint);
}
在ContactsListActivity中,原理是一样的。代码如下
ContactsListActivity
/**
* Run the query on a helper thread. Beware that this co
* on the main UI thread!
*/
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
return doFilter(constraint.toString());//doFilter()貌似实现了FilterQueryProvider的功能
}
doFilter
/**
* Called from a background thread to do the filter and return the resulting cursor.
*
* @param filter the text that was entered to filter on
* @return a cursor with the results of the filter
*/
Cursor doFilter(String filter) {
final ContentResolver resolver = getContentResolver();
switch (mMode) {
……
……
uri = Uri.withAppendedPath(mGroupFilterUri, Uri.encode(filter));
return resolver.query(uri,……);
}
throw new UnsupportedOperationException("filtering not allowed in mode " + mMode);
}