2016-02-04 110 views
0

我想把一個搜索按鈕放在操作欄上。我在屏幕上有一個列表,搜索任何文本列表將刷新並在相同的屏幕上顯示該文本數據。安卓菜單搜索按鈕

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    final MenuItem item = menu.findItem(R.id.search); 
    return true; 
} 

點擊搜索按鈕消費和軟鍵盤顯示搜索按鈕搜索。

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 

     case R.id.search: 
      // startSearchActivity(); 
      MenuItemCompat.expandActionView(item); 
      SearchView searchView = (SearchView) MenuItemCompat.getActionView(item); 

      searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 

       @Override 
       public boolean onQueryTextSubmit(String text) { 
        Toast.makeText(getApplicationContext(), "dddddd " + text, Toast.LENGTH_LONG).show(); 
        return true; 
       } 

       @Override 
       public boolean onQueryTextChange(String text) { 
        Toast.makeText(getApplicationContext(), "sssssss " + text, Toast.LENGTH_LONG).show(); 
        return true; 
       } 
      }); 
      break; 

     default: 
      break; 
    } 
    return super.onOptionsItemSelected(item); 
} 

但軟鍵盤的搜索按鈕沒有顯示任何操作。請告訴我什麼是錯..

回答

0

實施onCreateOptionsMenu,而不是setOnQueryTextListener onOptionsItemSelected

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     MenuItem searchItem = menu.findItem(R.id.search); 
     MenuItemCompat.expandActionView(searchItem); 

     SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); 

     searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 

      @Override 
      public boolean onQueryTextSubmit(String text) { 
       Toast.makeText(getApplicationContext(), "dddddd " + text, Toast.LENGTH_LONG).show(); 
       return true; 
      } 

      @Override 
      public boolean onQueryTextChange(String text) { 
       Toast.makeText(getApplicationContext(), "sssssss " + text, Toast.LENGTH_LONG).show(); 
       return true; 
      } 
     }); 
     return true; 
    }