2015-01-27 119 views
1

我有一個活動,顯示在標題欄中完美搜索,但現在我想要在搜索欄中輸入文字到一個字符串。請幫忙 !如何將在搜索欄中輸入的文本輸入到字符串中?

她是我的菜單/ XML

<?xml version="1.0" encoding="utf-8"?> 

<item android:id="@+id/action_search" 
     android:title="Search" 
     android:icon="@android:drawable/ic_menu_search" 
     android:showAsAction="always" 
     android:actionViewClass="android.widget.SearchView" 
     /> 


</menu> 

她是的onCreate

getWindow().requestFeature(Window.FEATURE_ACTION_BAR); 
    ActionBar actionBar = getActionBar(); 
     actionBar.setDisplayHomeAsUpEnabled(true); 

回答

3

你用過searchView的代碼?您可以使用下面的代碼:

@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 you can get the value "query" which is entered in the search box.** 

     } 
    }; 
    searchView.setOnQueryTextListener(queryTextListener); 

    return super.onCreateOptionsMenu(menu); 
} 
+0

哇,,,不錯的做工精細,感謝@bjiang – 2016-12-15 11:29:30

0

如果您使用的是工具欄,你可以這樣做:

MenuItem menuItem = getToolbar().getMenu().findItem(R.id.action_search); 
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem); 
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 
     @Override 
     public boolean onQueryTextSubmit(String query) { 
      Log.i("well", " this worked"); 
      return false; 
     } 

     @Override 
     public boolean onQueryTextChange(String newText) { 
      Log.i("well", " this worked"); 
      return false; 
     } 
    }); 
相關問題