2013-02-08 99 views
1

我尝试ActionBarSherlock搜索查看。 不幸的是搜索与福尔摩斯动作条搜索查看setOnKeyListener

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

没有被解雇。 你知道原因吗? 我这个职位 SearchView imeOptions and onQueryTextSubmit support ,用户以另一种方式解决了这个问题看。也许我应该这样做?

感谢

这里是我的代码:

@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; 
} 
+0

我有同样的问题。你有解决方案吗? – faizal 2013-12-17 16:49:07

回答

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; 
    } 
}); 

务必阅读the docs

+0

很好的答案,这个方法是好的。但看看我的问题,我目前有这个OnQueryTextListener的一些问题 – 2013-05-31 09:40:33