在android中实现搜索

时间:2014-04-12 06:01:54

标签: android

这是我代码的一部分..

SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search)
            .getActionView();
    searchView.setOnQueryTextListener(this);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    // searchManager.startSearch(oldval, selectInitialQuery, self, null, false);
    // searchView.setIconifiedByDefault(false);
    return super.onCreateOptionsMenu(menu);

这段代码在Activity中用于搜索..但我需要在Fragment中实现这段代码..需要做哪些更改?如何在片段中实现搜索?请帮助..

1 个答案:

答案 0 :(得分:0)

创建search_menu.xml
将此文件放在资源的菜单文件夹中

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    android:title="@string/app_name"
   yournamespace:actionViewClass="android.support.v7.widget.SearchView"
    yournamespace:showAsAction="always"/>

在覆盖onCreateOptionsMenu上创建活动。

在活动中编写以下代码

@覆盖     public boolean onCreateOptionsMenu(菜单菜单) {

MenuInflater inflater = getMenuInflater();             inflater.inflate(R.menu.activity_friends_search,menu);

        // Associate searchable configuration with the SearchView
    android.support.v7.widget.SearchView

        searchView = (SearchView) MenuItemCompat.getActionView(menu
                .findItem(R.id.action_search));
        AutoCompleteTextView searchText = (AutoCompleteTextView) searchView
                .findViewById(R.id.search_src_text);
        searchText.setHintTextColor(getResources().getColor(R.color.white));
        searchText.setTextColor(getResources().getColor(R.color.white));
        searchView.setQueryHint(getText(R.string.search_hint));
        searchText.requestFocus();
        searchView.setIconified(false);
        searchView.setOnQueryTextListener(new OnQueryTextListener() 
        {
            @Override
            public boolean onQueryTextChange(String query) {
            }
            @Override
            public boolean onQueryTextSubmit(String query) 
            {
            }   
        });

}