Create “history” to SearchView on ActionBar

后端 未结 2 696
故里飘歌
故里飘歌 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条回答
  •  旧时难觅i
    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:

    
        
        ...
    
    

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

    
    
    
    

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

提交回复
热议问题