现在的位置: 首页 > 综合 > 正文

关键字过滤器Filter

2012年12月18日 ⁄ 综合 ⁄ 共 10680字 ⁄ 字号 评论关闭

public abstract class

Filter

extends Object

java.lang.Object

        android.widget.Filter

Class Overview
关键字过滤器android.widget.Filter constrains data with a filtering pattern.

Filters are usually created by Filterable classes.

Filtering operations performed by calling
 filter(CharSequence) or filter(CharSequence, android.widget.Filter.FilterListener) are performed asynchronously. 

When these methods are called, a filtering request is posted in a request queue and processed later. 

Any call to one of these methods will cancel any previous non-executed filtering request.

注意1:Filter是个虚类。系统并没对外提供了的Filter类的实现,它只是内部实现了一些Filter类。Filter应该在UI线程中被创建。
注意2:Filter是对外提供filter(CharSequence) or filter(CharSequence, android.widget.Filter.FilterListener)来进行过滤。而且这两个函数是异步的。在调用这两个方法后,以前还未执行的过滤命令(它也通过调用者两个函数)将被取消。
主要函数
public CharSequence convertResultToString (Object resultValue)

Since: API Level 1

Converts a value from the filtered set into a CharSequence. Subclasses should override this method to convert their results. The default implementation returns an empty String for null values or the default String representation of the value.

Parameters

resultValue     the value to convert to a CharSequence

Returns


    * a CharSequence representing the value 

注1:该函数就是提供了把结果转化成字符串的功能。子类可以重载它。
public final void filter (CharSequence constraint, Filter.FilterListener listener)

Since: API Level 1


Starts an asynchronous filtering operation. Calling this method cancels all previous non-executed filtering requests and posts a new filtering request that will be executed later.


Upon completion, the listener is notified.

Parameters

constraint     the constraint used to filter the data

listener     a listener notified upon completion of the operation

注1:constraint是过滤的关键字。

注2:listener就是在过滤操作的一个监听器。当过滤完成时调用listener的    onFilterComplete(int count)。这里的count表示查询到的数据项的数量。
public final void filter (CharSequence constraint)

Since: API Level 1


Starts an asynchronous filtering operation. Calling this method cancels all previous non-executed filtering requests and posts a new filtering request that will be executed later.

Parameters

constraint     the constraint used to filter the data

注1:constraint是过滤的关键字。

Protected的且需要实现的方法:
protected abstract Filter.FilterResults performFiltering (CharSequence constraint)

Since: API Level 1

Invoked in a worker thread to filter the data according to the constraint. Subclasses must implement this method to perform the filtering operation. Results computed by the filtering operation must be returned as a Filter.FilterResults that will then be published in the UI thread through publishResults(CharSequence, android.widget.Filter.FilterResults).

Contract: When the constraint is null, the original data must be restored.

参数

constraint     the constraint used to filter the data

Returns


    * the results of the filtering operation

注1:该方法是个虚方法。

注2:该方法是在一个工作线程中执行的。它的任务就是根据关键字constraint来返回数据和数据的个数。

它们分别对应于Filter.FilterResults的成员变量public int     countpublic Object     values

protected abstract void publishResults (CharSequence constraint, Filter.FilterResults results)

Since: API Level 1


Invoked in the UI thread to publish the filtering results in the user interface. Subclasses must implement this method to display the results computed in performFiltering(CharSequence).

参数

constraint     the constraint used to filter the data

results     the results of the filtering operation

注1:该方法是虚方法。并且该方法是在创建Filter的线程中被执行,它一般用来做些UI方面的操作。如果Filter应该在UI线程中被创建,那么该函数就是UI thread中被执行了。

注意1:关于的实现可以参考CursorFilter。

Filter的源码摘要如下:
http://hi-android.info/src/android/widget/Filter.java.html
package android.widget;
public abstract class Filter {
    private static final String LOG_TAG = "Filter";
    
    private static final String THREAD_NAME = "Filter";
    private static final int FILTER_TOKEN = 0xD0D0F00D;
    private static final int FINISH_TOKEN = 0xDEADBEEF;

    private Handler mThreadHandler;
    private Handler mResultHandler;

    private Delayer mDelayer;

    private final Object mLock = new Object();

    /**

     * <p>Creates a new asynchronous filter.</p>

     */

    public Filter() {
        mResultHandler = new ResultsHandler();
    }

-----------------------------------省略----------------------------------------------------------
    public void setDelayer(Delayer delayer) {
        synchronized (mLock) {
            mDelayer = delayer;
        }
    }
-----------------------------------省略----------------------------------------------------------
    public final void filter(CharSequence constraint) {
        filter(constraint, null);
    }
-----------------------------------省略----------------------------------------------------------
    public final void filter(CharSequence constraint, FilterListener listener) {
        synchronized (mLock) {
            if (mThreadHandler == null) {
                HandlerThread thread = new HandlerThread(
                        THREAD_NAME, android.os.Process.THREAD_PRIORITY_BACKGROUND);
                thread.start();
                mThreadHandler = new RequestHandler(thread.getLooper());
            }

            final long delay = (mDelayer == null) ? 0 : mDelayer.getPostingDelay(constraint);
            
            Message message = mThreadHandler.obtainMessage(FILTER_TOKEN);
    
            RequestArguments args = new RequestArguments();
            // make sure we use an immutable copy of the constraint, so that

            // it doesn't change while the filter operation is in progress

            args.constraint = constraint != null ? constraint.toString() : null;
            args.listener = listener;
            message.obj = args;
    
            mThreadHandler.removeMessages(FILTER_TOKEN);
            mThreadHandler.removeMessages(FINISH_TOKEN);
            mThreadHandler.sendMessageDelayed(message, delay);
        }
    }
-----------------------------------省略----------------------------------------------------------
    protected abstract FilterResults performFiltering(CharSequence constraint);
-----------------------------------省略----------------------------------------------------------
    protected abstract void publishResults(CharSequence constraint,
            FilterResults results);
-----------------------------------省略----------------------------------------------------------
    public CharSequence convertResultToString(Object resultValue) {
        return resultValue == null ? "" : resultValue.toString();
    }
-----------------------------------省略----------------------------------------------------------
    protected static class FilterResults {
-----------------------------------省略----------------------------------------------------------
        public Object values;
-----------------------------------省略----------------------------------------------------------
        public int count;
    }
-----------------------------------省略----------------------------------------------------------
    public static interface FilterListener {
-----------------------------------省略----------------------------------------------------------
        public void onFilterComplete(int count);
    }
-----------------------------------省略----------------------------------------------------------
    private class RequestHandler extends Handler {
        public RequestHandler(Looper looper) {
            super(looper);
        }
-----------------------------------省略----------------------------------------------------------
        public void handleMessage(Message msg) {
            int what = msg.what;
            Message message;
            switch (what) {
                case FILTER_TOKEN:
                    RequestArguments args = (RequestArguments) msg.obj;
                    try {
                        args.results = performFiltering(args.constraint);
                    } catch (Exception e) {
                        args.results = new FilterResults();
                        Log.w(LOG_TAG, "An exception occured during performFiltering()!", e);
                    } finally {
                        message = mResultHandler.obtainMessage(what);

                        message.obj = args;

                        message.sendToTarget();

                    }

                    synchronized (mLock) {
                        if (mThreadHandler != null) {
                            Message finishMessage = mThreadHandler.obtainMessage(FINISH_TOKEN);
                            mThreadHandler.sendMessageDelayed(finishMessage, 3000);
                        }
                    }
                    break;
                case FINISH_TOKEN:
                    synchronized (mLock) {
                        if (mThreadHandler != null) {
                            mThreadHandler.getLooper().quit();
                            mThreadHandler = null;
                        }
                    }
                    break;
            }
        }
    }

    /**

     * <p>Handles the results of a filtering operation. The results are

     * handled in the UI thread.</p>

     */

    private class ResultsHandler extends Handler {
        /**

         * <p>Messages received from the request handler are processed in the

         * UI thread. The processing involves calling

         * {@link Filter#publishResults(CharSequence,

         * android.widget.Filter.FilterResults)}

         * to post the results back in the UI and then notifying the listener,

         * if any.</p> 

         *

         * @param msg the filtering results

         */

        @Override
        public void handleMessage(Message msg) {
            RequestArguments args = (RequestArguments) msg.obj;

            publishResults(args.constraint, args.results);
            if (args.listener != null) {
                int count = args.results != null ? args.results.count : -1;
                args.listener.onFilterComplete(count);
            }
        }
    }
-----------------------------------省略----------------------------------------------------------
    private static class RequestArguments {
        /**

         * <p>The constraint used to filter the data.</p>

         */

        CharSequence constraint;

        /**

         * <p>The listener to notify upon completion. Can be null.</p>

         */

        FilterListener listener;

        /**

         * <p>The results of the filtering operation.</p>

         */

        FilterResults results;
    }

    /**
     * @hide
     */
    public interface Delayer {

        /**

         * @param constraint The constraint passed to {@link Filter#filter(CharSequence)}

         * @return The delay that should be used for

         *         {@link Handler#sendMessageDelayed(android.os.Message, long)}

         */

        long getPostingDelay(CharSequence constraint);
    }
}

注意:如果在完成一个过滤任何后,3000毫秒的时间内没有新的过滤任务请求的话,mThreadHandler会消亡。

在新的过滤任务到来时如果mThreadHandler已经消亡,那么就重新创建一个新的mThreadHandler。

抱歉!评论已关闭.