developer's guide 中看似矛盾的地方让我有点困惑.在“决定是否需要 ContentProvider”一节中,它首先声明如果“您想使用搜索框架提供自定义搜索建议”,您需要这样做。紧接着它说“如果使用完全在你自己的应用程序中,你不需要提供者来使用 SQLite 数据库。”如果我为 SearchView 提供的数据在 SQLite 数据库中,而我没有计划将此数据共享给除此应用程序本身以外的任何其他应用程序?
最佳答案
What if the data I'm providing for SearchView is in the SQLite database and I don't plan to share this data to any other application other than this application itself?
然后你有一个选择:
创建一个
ContentProvider
并使用搜索框架。如果您决定创建一个ContentProvider
,您可以配置搜索建议在 XML 中。这是遗留
SearchableDictionary
示例应用程序中的示例:首先您需要一个“可搜索的 Activity ”。这在 list 中声明如下:
<application ... > <activity android:name=".SearchableActivity" > <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/> </activity> ... </application>
注意元数据中指定的可搜索资源。它可能看起来像这样:
<searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/search_label" android:hint="@string/search_hint" android:searchSettingsDescription="@string/settings_description" android:searchSuggestAuthority="com.example.android.searchabledict.DictionaryProvider" android:searchSuggestIntentAction="android.intent.action.VIEW" android:searchSuggestIntentData="content://com.example.android.searchabledict.DictionaryProvider/dictionary" android:searchSuggestSelection=" ?" android:searchSuggestThreshold="1" android:includeInGlobalSearch="true" > </searchable>
然后
SearchView
设置如下:SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false);
这样做的其他好处是a)您可以让
ContentProvider
在对特定内容 URI 进行任何更新时通知您,b ) 如果您最终决定让您的数据与其他应用共享,那么您已经完成了大部分工作。有关更多信息,请参阅以下链接:
不要使用搜索框架。您不需要为搜索建议提供
ContentProvider
,但您仍然需要做一些使用代码设置以使您的搜索和建议有效。您需要使用setSuggestionsAdapter()
向SearchView
提供一个CursorAdapter
,并且您需要设置一个OnQueryTextListener
以触发对CursorAdapter
的过滤。此外,当在
SearchView
中按下 Enter 或从建议中选择建议时,您必须编写代码以使用startActivity
启动可搜索 Activity 列表。
没有正确或错误的方法,只有不同的方法。您必须查看这两种策略,然后决定哪一种最适合您应用的设计目标。
关于android - 如果数据不共享给其他应用程序,ContentProvider 对于 SearchView 来说是多余的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104599/