如何将在搜索操作栏中输入的文本输入字符串?

时间:2013-10-25 11:15:38

标签: android android-actionbar

我正在尝试使用搜索创建操作栏。 我可以创建搜索栏。如何才能将字段中输入的文本输入字符串?搜索操作栏有什么好的代码吗?

我做的是

SearchManager searchManager =
           (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView =
            (SearchView) menu.findItem(R.id.menu_search).getActionView();



    Intent intent = getIntent();
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
      String search = intent.getStringExtra(SearchManager.QUERY);

1 个答案:

答案 0 :(得分:51)

您可以像这样使用搜索栏。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.main, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search)
            .getActionView();
    if (null != searchView) {
        searchView.setSearchableInfo(searchManager
                .getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);
    }

    SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
        public boolean onQueryTextChange(String newText) {
            // this is your adapter that will be filtered
            return true;
        }

        public boolean onQueryTextSubmit(String query) {
            //Here u can get the value "query" which is entered in the search box.

        }
    };
    searchView.setOnQueryTextListener(queryTextListener);

    return super.onCreateOptionsMenu(menu);
}