我正在开发以下屏幕:
1个屏幕截图
在工具栏上,我有一个搜索图标。要添加此搜索图标,我使用了以下代码:
menu_friend_list_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@drawable/search"
android:orderInCategory="100"
android:title="@string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
</menu>
活动内的代码
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_friend_list_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(getApplicationContext(), "Search button clicked", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
点击搜索图标我想在工具栏中显示SearchView(如果我这里没错)。简而言之,我想实现以下屏幕:
请告诉我如何实现这一点。对于不同的片段,搜索会有所不同。
答案 0 :(得分:4)
试试这个
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_actions, menu);
MenuItem searchViewItem = menu.findItem(R.id.action_search);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) searchViewItem.getActionView();
searchView.setQueryHint("Search for Product,Brands...");
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);// Do not iconify the widget; expand it by defaul
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
// This is your adapter that will be filtered
Toast.makeText(getApplicationContext(),"textChanged :"+newText,Toast.LENGTH_LONG).show();
return true;
}
public boolean onQueryTextSubmit(String query) {
// **Here you can get the value "query" which is entered in the search box.**
Toast.makeText(getApplicationContext(),"searchvalue :"+query,Toast.LENGTH_LONG).show();
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return true;
}
答案 1 :(得分:0)
你没有正确地夸大菜单,这是你应该如何膨胀以获得你想要的屏幕
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.yourmenyxml, menu);
item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
答案 2 :(得分:0)
我有类似的问题。我解决如下:
MenuItem searchItem = menu.findItem(R.id.ot_action_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchItem.expandActionView();
searchView.setIconified(false);
searchView.setQuery(searchQuery, false);
注意:expandActionView()应该在searchItem菜单项而不是searchView上调用。那是我的错误。
答案 3 :(得分:-1)
只需在片段中实现搜索而不是活动。