4

我想在我的 SearchView 上有历史,我一直在谷歌搜索,我发现的唯一明智的(?)教程是这个,但这只是像 Gingerbread 一样,而不是 API>14。

然后我找到了这段代码:

String[] columnNames = {"_id","text"};
        MatrixCursor cursor = new MatrixCursor(columnNames);
        String[] array = {"Snääälla", "bla bla bla", "Jävla piss"}; //if strings are in resources
        String[] temp = new String[2];
        int id = 0;
        for(String item : array){
            temp[0] = Integer.toString(id++);
            temp[1] = item;
            cursor.addRow(temp);
        }
        String[] from = {"text"};
        int[] to = {android.R.id.text1};
        CursorAdapter ad = new SimpleCursorAdapter(this.getActivity(), android.R.layout.simple_list_item_1, cursor, from, to);
        mSearchView.setSuggestionsAdapter(ad);

而且该代码只工作了一半,因为它没有显示您已经编写的结果,它显示了所有项目。

我只是希望它看起来像这样:

Google Play 商店截图

这是我当前添加 SearchView 的代码:

资源/菜单/menu.xml:

<item android:id="@+id/fragment_searchmenuitem"
      android:icon="@drawable/ic_search_white"
      android:title="@string/menu_search"
      android:showAsAction="collapseActionView|ifRoom"
      android:actionViewClass="android.widget.SearchView" />

MainActivity.java:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if(!mDrawerLayout.isDrawerOpen(mDrawerList)) {
        inflater.inflate(R.menu.fragment_search, menu);

        mMenuItem = menu.findItem(R.id.fragment_searchmenuitem);
        mSearchView = (SearchView) mMenuItem.getActionView();
        mMenuItem.expandActionView();
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                mMenuItem.collapseActionView();
                searchSupport.SearchForLyrics(s);
                actionBar.setSubtitle("Searcing for: " + s);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }
        });
    }

    super.onCreateOptionsMenu(menu, inflater);
}

有人可以给我一些开始,说实话我不知道从哪里开始。所以任何帮助将不胜感激。

4

2 回答 2

6

本页讨论如何为 SearchView 实现历史记录。

http://developer.android.com/guide/topics/search/adding-recent-query-suggestions.html

首先,您必须创建一个内容提供者:

public class MySuggestionProvider extends SearchRecentSuggestionsProvider {
    public final static String AUTHORITY = "com.example.MySuggestionProvider";
    public final static int MODE = DATABASE_MODE_QUERIES;

    public MySuggestionProvider() {
        setupSuggestions(AUTHORITY, MODE);
    }
}

然后在您的应用程序清单中声明内容提供者,如下所示:

<application>
    <provider android:name=".MySuggestionProvider"
              android:authorities="com.example.MySuggestionProvider" />
    ...
</application>

然后将内容提供者添加到您的可搜索配置中,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_label"
    android:hint="@string/search_hint"
    android:searchSuggestAuthority="com.example.MySuggestionProvider"
    android:searchSuggestSelection=" ?" >
</searchable>

您可以随时调用 saveRecentQuery() 来保存查询。以下是您可以在活动的 onCreate 方法中执行此操作的方法:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent intent  = getIntent();

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
        suggestions.saveRecentQuery(query, null);
    }
}

要清除搜索历史,您只需像这样调用SearchRecentSuggestions的方法clearHistory()

SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
        HelloSuggestionProvider.AUTHORITY, HelloSuggestionProvider.MODE);
suggestions.clearHistory();
于 2014-09-03T13:02:09.763 回答
0

我在 ActionBar 上为 SeaarchView 使用 Fragment,所以我有自己的侦听器,例如“setOnSuggestionListener”、“setOnQueryTextListener”。当我编写 searchview.setSearchableInfo() 时,我的适配器停止工作。因此,我查看了“setSearchableInfo”函数,并从核心代码中提取了一些用于自己获取历史搜索数据的代码。

class MySearchableInfoClass internal constructor(
private val mContext: Context,
private val mSearchable: SearchableInfo
 ) {

private val QUERY_LIMIT = 5


private fun getSearchManagerSuggestions(
    searchable: SearchableInfo?,
    query: String,
    limit: Int
): Cursor? {
    if (searchable == null) {
        return null
    }

    val authority = searchable.suggestAuthority ?: return null

    val uriBuilder = Uri.Builder()
        .scheme(ContentResolver.SCHEME_CONTENT)
        .authority(authority)
        .query("")  // TODO: Remove, workaround for a bug in Uri.writeToParcel()
        .fragment("")  // TODO: Remove, workaround for a bug in Uri.writeToParcel()

    // if content path provided, insert it now
    val contentPath = searchable.suggestPath
    if (contentPath != null) {
        uriBuilder.appendEncodedPath(contentPath)
    }

    // append standard suggestion query path
    uriBuilder.appendPath(SearchManager.SUGGEST_URI_PATH_QUERY)

    // get the query selection, may be null
    val selection = searchable.suggestSelection
    // inject query, either as selection args or inline
    var selArgs: Array<String>? = null
    if (selection != null) {    // use selection if provided
        selArgs = arrayOf(query)
    } else {                    // no selection, use REST pattern
        uriBuilder.appendPath(query)
    }

    if (limit > 0) {
        uriBuilder.appendQueryParameter("limit", limit.toString())
    }

    val uri = uriBuilder.build()

    // finally, make the query
    return mContext.contentResolver.query(uri, null, selection, selArgs, null)
}

fun getSearchHistoryCursor(constraint: CharSequence?): Cursor? {
    val query = constraint?.toString() ?: ""
    var cursor: Cursor? = null

    try {
        cursor = getSearchManagerSuggestions(mSearchable, query, QUERY_LIMIT)
        // trigger fill window so the spinner stays up until the results are copied over and
        // closer to being ready
        if (cursor != null) {
            cursor.count
            return cursor
        }
    } catch (e: RuntimeException) {

    }

    // If cursor is null or an exception was thrown, stop the spinner and return null.
    // changeCursor doesn't get called if cursor is null
    return null
}
}

getSearchHistoryCursor 返回一个光标,因此您可以获取字符串或其他任何内容,并最终搜索历史记录。

例子:

cursor.getString(cursor.getColumnIndex("suggest_text_1")))
于 2020-12-09T15:32:58.163 回答