现在的位置: 首页 > 综合 > 正文

how to use onSearchRequested on Fragment

2017年10月14日 ⁄ 综合 ⁄ 共 1376字 ⁄ 字号 评论关闭

    最近项目版本更新,由原来的多个activity转换成了一个主activity和多个fagment,然后牵涉到一个fragment中的搜索功能,此功能的实现不能想旧版本那样处理了。我的方法如下:

    1.先在Android Manifest.xml对主activity写这些代码:

         <intent-filter>
                <action android:name="android.intent.action.SEARCH" /> //过滤搜索功能
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
            </intent-filter>
            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" //对实现请求搜索功能的配置
                android:value="xx.xx.xx.xx" /> //在哪个activity中展示搜索的结果(activity所在的路径)

   2.searchable.xml的配置(必须的配置文件)

       <searchable xmlns:android="http://schemas.android.com/apk/res/android"
        android:hint="@string/search_hint"
      android:label="@string/search_label"
      android:searchMode="showSearchLabelAsBadge"
      android:searchSuggestAuthority="xx.SearchSuggestionSampleProvider"//SearchSuggestionSampleProvider.java文件所在的包名
       android:searchSuggestSelection=" ? " />

3.调用onSearchRequested ()的方法

   getActivity().onSearchRequested  ();

以上三步只是完成了对系统搜索功能的请求,但并没有完成搜索功能,还差最后一步:

 4.在要显示结果的主activity中获取搜索框中的值

       if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {//如果执行的是搜索操作
query = getIntent().getStringExtra(SearchManager.QUERY);//获取搜索框中的值
switchToDiary(query); 
}

 /**

   * 对获取到的值进行处理,最好是转到该fragment中处理,记得把query的值传过去

   */

 public void switchToDiary(String quey){

 //跳转到需要的Fragment,进行数据处理

}

以上就是我的拙见,希望可以帮助到被这个问题困扰的程序员们,如果有什么问题,可以随时发表评论,我会及时回答的

抱歉!评论已关闭.