Create “history” to SearchView on ActionBar

后端 未结 2 695
故里飘歌
故里飘歌 2020-12-17 04:04

I want to have history on my SearchView, I\'ve been googling around, and the only sensible(?) tutorial I found was this, but that\'s just for like Gingerbread, not API>14.

相关标签:
2条回答
  • 2020-12-17 04:50

    This page talks about how you can implement history for SearchView.

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

    First, you have to create a content provider:

    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);
        }
    }
    

    Then declare the content provider in your application manifest like this:

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

    Then add the content provider to your searchable configurations like this:

    <?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>
    

    You can call saveRecentQuery() to save queries at any time. Here's how you can do it in the onCreate method for your activity:

    @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);
        }
    }
    

    To clear search history you simply need to call SearchRecentSuggestions's method clearHistory() like this:

    SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
            HelloSuggestionProvider.AUTHORITY, HelloSuggestionProvider.MODE);
    suggestions.clearHistory();
    
    0 讨论(0)
  • 2020-12-17 05:02

    I am using Fragment for SeaarchView on ActionBar so I have my own listener like "setOnSuggestionListener", "setOnQueryTextListener". When I write searchview.setSearchableInfo(), my adapter stops working. So I looked at "setSearchableInfo" function and I extract some code for getting history search data myself from core code.

    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 returns a cursor so you can getString or anythingelse and eventually search history.

    Example:

    cursor.getString(cursor.getColumnIndex("suggest_text_1")))
    
    0 讨论(0)
提交回复
热议问题