1

我正在尝试 ActionBarSherlock SearchView。不幸的是

       public boolean onKey(View arg0, int arg1, KeyEvent event)

没有被解雇。你知道原因吗?我从这篇文章 SearchView imeOptions 和 onQueryTextSubmit 支持 中看到用户以另一种方式解决了问题。也许我也应该这样做?

谢谢

这是我的代码:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //Used to put dark icons on light action bar
    boolean isLight = SampleList.THEME == R.style.Theme_Sherlock_Light;

    //Create the search view
   final SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
    searchView.setQueryHint("Search for countries…");

    System.out.println("searchView.getQuery()"+searchView.getQuery());

    searchView.setOnKeyListener(new OnKeyListener()
    {
    /**
      * This listens for the user to press the enter button on
      * the keyboard and then hides the virtual keyboard
      */
           @Override
        public boolean onKey(View arg0, int arg1, KeyEvent event) {
        // If the event is a key-down event on the "enter" button

               System.out.println("--->"+searchView.getQuery());
        if ( (event.getAction() == KeyEvent.ACTION_DOWN ) &&
        (arg1 == KeyEvent.KEYCODE_ENTER) )
        {
        InputMethodManager imm = (InputMethodManager)     SearchViews.this.getSystemService(SearchViews.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
        return true;
        }
        return false;
        }



    } );

    menu.add("Search")
        .setIcon(isLight ? R.drawable.ic_search_inverse : R.drawable.abs__ic_search)
        .setActionView(searchView)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

    return true;
}
4

1 回答 1

6

避免做这样的事情。使用SearchView.OnQueryTextListener

final SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setQueryHint("Search for countries..");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }


    @Override
    public boolean onQueryTextSubmit(String query) {
        if (query.length() != 0) {
            System.out.println("--->" + query);
            // handle search here
            return true;
        }
        return false;
    }
});

始终阅读文档

于 2013-02-08T12:40:04.967 回答