2013-10-25 109 views
17

我正在嘗試使用搜索創建一個操作欄。 我可以創建搜索欄。如何讓字段中輸入的文本字符串?有搜索行爲欄的好代碼嗎?如何讓在搜索欄中輸入的文字在字符串中顯示?

我做什麼是

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

回答

49

您可以使用搜索欄是這樣的。

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

哇,好,它的工作很好,謝謝。 –

相關問題