Android searchview的建议来自网络

标签 android android-searchmanager

我在 Actionbar 中有一个 SearchView,我希望从服务中获取建议。

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

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

最佳答案

因此,如果您在项目中使用搜索 View 并希望显示建议,您可以通过两种方法实现

/**
         * 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”等等,

所以最好是在用户停止在搜索 View 中输入时点击服务器,您可以使用这样的处理程序和可运行的东西来处理它。

         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 应用相同的逻辑. 希望对您有所帮助。

关于Android searchview的建议来自网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14018970/

相关文章:

Android Studio 3.1 gradle 构建抛出 java.util.zip.ZipException

android - 在 Android 的 Action Bar 中实现 SearchView

java - 如何在Android中将2个TextView与if else条件放在同一位置

java - 即使在将适配器设置为布局管理器之后,我也面临着 RecyclerView 没有附加适配器的问题。我一个

android - 如何让SearchView在重新打开后保留上一次的查询内容?

Android 自定义搜索建议 : Query Two Parameters

android - 打开全局搜索作为覆盖

更改设备语言时更改了 Android APK 名称?

android - 如何使用 Fiddler4 从 Android App 捕获 HTTPS(TLS 1.0) 通信?