来自网络的Android searchview建议

时间:2012-12-24 08:29:36

标签: android android-searchmanager

我在操作栏中有一个SearchView,我希望从服务中获取该建议。

我在android Samples Searchable Dictionary中看过一个示例。但它正在从本地数据库加载结果。

我明白了,有必要使用Content Provider。 但我想知道何时从Web服务获取结果。我的意思是什么时候打网络。 请任何人都可以帮忙。

1 个答案:

答案 0 :(得分:0)

因此,如果您在项目中使用搜索查看并希望显示可以实施的建议,那么有两种方法

/**
         * Called when the user submits the query. This could be due to a key press on the
         * keyboard or due to pressing a submit button.
         * The listener can override the standard behavior by returning true
         * to indicate that it has handled the submit request. Otherwise return false to
         * let the SearchView handle the submission by launching any associated intent.
         *
         * @param query the query text that is to be submitted
         *
         * @return true if the query has been handled by the listener, false to let the
         * SearchView perform the default action.
         */
        boolean onQueryTextSubmit(String query);

        /**
         * Called when the query text is changed by the user.
         *
         * @param newText the new content of the query text field.
         *
         * @return false if the SearchView should perform the default action of showing any
         * suggestions if available, true if the action was handled by the listener.
         */
        boolean onQueryTextChange(String newText);

从文档中可以看出这些方法是如何工作的。 因此,只要用户输入onQueryTextChange方法就会被调用,每次输入或删除新关键字时都会调用它。

在此方法中,您可以调用服务器以获取建议并将其提供给用户。

现在,如果用户想要搜索例如。 “apple”所以对每个关键字命中服务器是没有意义的,比如命中服务器为“a”,然后在“app”之后的“ap”等等,

所以一旦用户在搜索视图中输入你可以使用处理程序处理并且可以运行这样的东西,最好点击服务器。

         Handler mHandler;
         String mQueryText;


         @Override
            public boolean onQueryTextChange(final String newText) {
                mQueryText=newText;
                //Make if invisible once you get the data.
                mProgressBar.setVisibility(View.VISIBLE);
                mHandler.removeCallbacks(mRunnable);
                mHandler.postDelayed(mRunnable,200);
                return true;
                }

    private Runnable mRunnable  =new Runnable() {
        @Override
        public void run() {

      //Hit server here.

        }
    };

虽然您可以点击服务器并获取数据,但您可以显示进度条或其他内容。

您可以使用EditText https://developer.android.com/reference/android/widget/EditText.html应用相同的逻辑。 希望它有所帮助。