如何使用http请求在操作栏中实现搜索视图自动完成功能? [英] How to implement search view autocomplete in actionbar using http request?

查看:123
本文介绍了如何使用http请求在操作栏中实现搜索视图自动完成功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在操作栏中添加了搜索视图小部件并希望处理自动完成功能.写了3个以上的字母后,它应该满足对我的Web API的http请求,这将返回json结果并显示搜索小部件建议. 但是在文档中,内容提供商的情况如此.如何组织自动完成功能?

I've added search view widget to my action bar and would like to handle autocomplete feature. After writing more then 3 letters it should fulfill http request to my web API which will return json result and should show search widget suggestions. But in documentation is observed the case with content providers. How can I organize autocomplete feature?

在菜单xml文件中添加了搜索视图:

Added search view in menu xml file:

    <item android:id="@+id/search"
    android:icon="@drawable/ic_search_white_24dp"
    android:title="Search"
    [namespace]:showAsAction="always"
    [namespace]:actionViewClass="android.widget.SearchView" />

将可搜索的配置与SearchView相关联:

Associates searchable configuration with the SearchView:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.navigation, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    return super.onCreateOptionsMenu(menu);
}

添加了可搜索的配置:

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint"
    android:searchSuggestAuthority="com.my.domain.searchable_activity" />

并最终添加了空的负责任的活动.

And ultimately added empty responsible activity.

推荐答案

使用setSearchableInfo()和搜索配置无法执行此操作.

You can't do this with setSearchableInfo() and a search configuration.

问题是SearchView需要一个CursorAdapter,并且您正在从服务器而不是数据库中检索数据.

The problem is that SearchView needs a CursorAdapter and you are retrieving data from the server, not the database.

但是,在执行以下步骤之前,我已经做了类似的事情:

However, I have done something like this before with these steps:

  • 设置您的SearchView以使用CursorAdapter;

    searchView.setSuggestionsAdapter(new SimpleCursorAdapter(
            context, android.R.layout.simple_list_item_1, null, 
            new String[] { SearchManager.SUGGEST_COLUMN_TEXT_1 }, 
            new int[] { android.R.id.text1 }));

  • 创建一个AsyncTask以从您的服务器读取JSON数据,然后从该数据中创建一个MatrixCursor:

  • Create an AsyncTask to read the JSON data from your server and create a MatrixCursor from the data:

    public class FetchSearchTermSuggestionsTask extends AsyncTask<String, Void, Cursor> {
    
        private static final String[] sAutocompleteColNames = new String[] { 
                BaseColumns._ID,                         // necessary for adapter
                SearchManager.SUGGEST_COLUMN_TEXT_1      // the full search term
        };
    
        @Override
        protected Cursor doInBackground(String... params) {
    
            MatrixCursor cursor = new MatrixCursor(sAutocompleteColNames);
    
            // get your search terms from the server here, ex:
            JSONArray terms = remoteService.getTerms(params[0]);
    
            // parse your search terms into the MatrixCursor
            for (int index = 0; index < terms.length(); index++) {
                String term = terms.getString(index);
    
                Object[] row = new Object[] { index, term };
                cursor.addRow(row);
            }
    
            return cursor;
        }
    
        @Override
        protected void onPostExecute(Cursor result) {
            searchView.getSuggestionsAdapter().changeCursor(result);
        }
    
    }
    

  • 设置OnQueryTextListener以启动远程服务器任务或开始搜索活动:

  • Set an OnQueryTextListener to kick off your remote server task or start your search activity:

        searchView.setOnQueryTextListener(new OnQueryTextListener() {
    
            @Override
            public boolean onQueryTextChange(String query) {
    
                if (query.length() >= SEARCH_QUERY_THRESHOLD) {
                    new FetchSearchTermSuggestionsTask().execute(query);
                } else {
                    searchView.getSuggestionsAdapter().changeCursor(null);
                }
    
                return true;
            }
    
            @Override
            public boolean onQueryTextSubmit(String query) {
    
                // if user presses enter, do default search, ex:
                if (query.length() >= SEARCH_QUERY_THRESHOLD) {
    
                    Intent intent = new Intent(MainActivity.this, SearchableActivity.class);
                    intent.setAction(Intent.ACTION_SEARCH);
                    intent.putExtra(SearchManager.QUERY, query);
                    startActivity(intent);
    
                    searchView.getSuggestionsAdapter().changeCursor(null);
                    return true;
                }
            }
        });
    

  • SearchView上设置OnSuggestionListener以执行搜索:

  • Set an OnSuggestionListener on the SearchView to execute your search:

        searchView.setOnSuggestionListener(new OnSuggestionListener() {
    
            @Override
            public boolean onSuggestionSelect(int position) {
    
                Cursor cursor = (Cursor) searchView.getSuggestionsAdapter().getItem(position);
                String term = cursor.getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));
                cursor.close();
    
                Intent intent = new Intent(MainActivity.this, SearchableActivity.class);
                intent.setAction(Intent.ACTION_SEARCH);
                intent.putExtra(SearchManager.QUERY, term);
                startActivity(intent);
    
                return true;
            }
    
            @Override
            public boolean onSuggestionClick(int position) {
    
                return onSuggestionSelect(position);
            }
        });
    

  • 这篇关于如何使用http请求在操作栏中实现搜索视图自动完成功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆