我试图在操作栏上放置一个搜索按钮。我在屏幕上有一个列表,在搜索任何文本列表时将刷新并在同一屏幕上显示该文本数据。
@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 :(得分: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;
}