I've tried a million ways to place the SearchView in my snippet. I read the documentation and tutorials all day long and nothing worked. I stopped at this:
search_menu.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:title="#string/app_name"
android:icon="#drawable/ic_baseline_search_24"
app:showAsAction="collapseActionView|ifRoom"
/>
</menu>
java code
public class Search_offer extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
return inflater.inflate(R.layout.activity_search_offer,container,false);
}
public void onStart(){
super.onStart();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.search_menu, menu);
MenuItem item = menu.findItem(R.id.search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
}
I can't figure out why it's not showing in any way. Help please
Could you run it and show compilation or run errors?
I think, I don't get the problem fully.
Here's some tips for menus:
When you are starting you can use app:showAsAction="always"
In that case small icon, which you choose should apesr in the app bar. So you can do it to chcech if image appears at all (to learn).
Second of all - probably program have a problem to find a SearchView, because you forgot to add "app:actionVieClass". In that case your code should throw error during calling this line (SearchView) item.getActionVie().
Checkout this video - maybe it will be helpfull: https://youtu.be/9OWmnYPX1uc
I have implemented searchview in actionbar and it is working fine. In viewpager if user switch between fragment I want to keep the state of searchview, to do so whenever fragment switch I applied query and show search result in recycler until now it is working like charm except I want to expand my searchview and put a query into it on fragment change method. I have seen lots of thread on it and I have applied multiple solutions none worked.
<?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/ic_search_black_24dp"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="Search"/>
</menu>
In onCreateOptionsMenu i am inflating my menu.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main2, menu);
this.menu = menu;
searchActionBar(menu);
super.onCreateOptionsMenu(menu, inflater);
}
In search Actionbar i am fetching query result and save query text to mQuery and clear this text when searchview collapse.
private void searchActionBar(Menu menu){
searchViewItem = menu.findItem(R.id.action_search);
searchViewAndroidActionBar = (SearchView) MenuItemCompat.getActionView(searchViewItem);
searchViewAndroidActionBar.setIconifiedByDefault(false);
searchViewAndroidActionBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#SuppressLint("RestrictedApi")
#Override
public boolean onQueryTextSubmit(String query) {
searchViewAndroidActionBar.clearFocus();
mQuery = query;
fetchSearchResult(query);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchViewItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
mQuery="";
return true;
}
});
}
This function is called when fragment switch in viewpager , if there is any query I want to set in searchview. But searchview doesn't expand. Although query submit function is running.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isResumed() && isVisibleToUser) {
if (searchViewAndroidActionBar != null) {
searchViewAndroidActionBar.setFocusable(true);
searchViewAndroidActionBar.setQuery(mQuery,true);
}
}
}
Any help would be appreciated.
I am wondering how to show searchview in actionbar only in parent fragment. For now, when I submit a search from searchview in actionbar and go to next fragment, I still can see the searchview in my child fragment. Any suggestions to fix that? Thanks.
For now, in my parent class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the options menu from XML
inflater.inflate(R.menu.homesearchbar, menu);
super.onCreateOptionsMenu(menu,inflater);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Bundle bundle = new Bundle();
bundle.putString("HomeToSearch_keyword", query);
SearchVC searchVC = new SearchVC();
searchVC.setArguments(bundle);
getFragmentManager().beginTransaction().add(R.id.HomeVC_frameChildFragment, searchVC)
.addToBackStack(null)
.commit();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
homesearchbar.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:title=""
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"/>
</menu>
To hide searchView inside child fragment override inside it onPrepareOptionsMenu method. Then inside that method you can do something like this: menu.findItem(R.id.search).setVisible(false); or eventually when needed you can change it to true. And also don't forget to override onCreate method where you will put setHasOptionsMenu(true);
Trying to include a searchview in actionbar. For this, I have done the following:
Created MenuSearch.xml in the menu folder as given below:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_search"
android:actionViewClass="Android.Support.V7.Widget.SearchView"
android:icon="#android:drawable/ic_menu_search"
android:showAsAction="always"
android:title="Search"/>
</menu>
Included the method OnCreateOptionsMenu in the fragment:
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
inflater.Inflate(Resource.Menu.MenuSearch, menu);
base.OnCreateOptionsMenu(menu, inflater);
var searchManager = (SearchManager) this.Activity.GetSystemService(Context.SearchService);
searchView = (SearchView) (menu.FindItem(Resource.Id.action_search).ActionView);
searchView.SetSearchableInfo(searchManager.GetSearchableInfo(Activity.ComponentName));
}
And I have set HasOptionsMenu = true; in oncreate of the fragment.
With the code above, I get null pointer in the line searchView.SetSearchableInfo... . Not sure why this happens, though everything seem to be correct and in place.
Based on some suggestions for resolving similar issue, I have also tried out the below option for searchview.
var item = menu.FindItem (Resource.Id.action_search);
var searchItem = MenuItemCompat.GetActionView(item);
searchView = searchItem.JavaCast<Android.Support.V7.Widget.SearchView>();
searchView.SetSearchableInfo(searchManager.GetSearchableInfo(Activity.ComponentName));
But again, I get searchView as null.
Now that I have tried the possible options, I am clueless as to why searchview becomes null.
Any help is much appreciated.
Change your MenuSearch.xml to
<?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:title="#string/app_name"
android:icon="#drawable/ic_action_search"
app:showAsAction="collapseActionView|ifRoom"
/>
</menu>
And in your fragment, add searchView.setOnQueryTextListener
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.search_option_menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = new SearchView(((MainActivity) mContext).getSupportActionBar().getThemedContext());
// MenuItemCompat.setShowAsAction(item, //MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | //MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
// MenuItemCompat.setActionView(item, searchView);
// These lines are deprecated in API 26 use instead
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM);
item.setActionView(searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
);
}
Answer updated for 2018. Sorry for Kotlin, if you're using Java.
Your xml menu resource (search_menu.xml for example):
<?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:title="#string/app_name"
android:icon="#drawable/ic_search"
app:showAsAction="collapseActionView|ifRoom"
/>
</menu>
Build-up code:
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
menu.clear()
inflater?.inflate(R.menu.search_menu, menu)
val searchView = SearchView((context as MainActivity).supportActionBar?.themedContext ?: context)
menu.findItem(R.id.action_search).apply {
setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW or MenuItem.SHOW_AS_ACTION_IF_ROOM)
actionView = searchView
}
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
return false
}
})
searchView.setOnClickListener {view -> }
}
You'll probably also need to put this line in onCreate() (worked for my fragment) to get this all to appear:
setHasOptionsMenu(true)
For late 2018 and for apis >= 26 compatible (deprecation warnings) and a properly formatted answer:
The menu.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:title="Search_change_me_with_proper_id"
android:icon="#drawable/ic_action_search"
app:showAsAction="collapseActionView|ifRoom"/>
</menu>
Java code inside the ActivityFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true); // Add this!
return inflater.inflate(R.layout.fragment_add_app, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_add_app, menu);
MenuItem item = menu.findItem(R.id.action_search_menu_add_app);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// Here is where we are going to implement the filter logic
return true;
}
});
}
OR as a second option you let the ActivityFragment implement SearchView.OnQueryTextListener and then use the menu search:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true); // Add this! (as above)
return inflater.inflate(R.layout.fragment_add_app, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_add_app, menu);
MenuItem item = menu.findItem(R.id.action_search_menu_add_app);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(this); // Fragment implements SearchView.OnQueryTextListener
}
#Override
public boolean onQueryTextChange(String query) {
// Here is where we are going to implement the filter logic
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
i solved this issue i wants to share my answer for searchView NullPointerException
we need to remove below method from Main Activity
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return true;
and use inside fragment in OnActivityCreated setHasOptionsMenu(true)
and Override methods
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_search:
// onCall(); //your logic
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Your search_options_menu.xml should look like this:
<?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:title="#string/app_name"
android:icon="#drawable/ic_action_search"
app:showAsAction="collapseActionView|ifRoom"
/>
</menu>
Override onCreateOptionMenu method in your fragment setHasOptionsMenu(true); inside onCreate() on your fragment.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.search_option_menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
MenuItemCompat.setActionView(item, searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//Do search code here
return true;
}
});
}
search_view.setOnQueryTextListener(object: SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(query: String?): Boolean {
adapter.filter.filter(query)
return true
}
})
And don't add the intent filter for your activity in Manifest file.
In my fragment's onCreateOptionsMenu the code
SearchManager searchManager =
(SearchManager)getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchableInfo searchableInfo =
searchManager.getSearchableInfo(getActivity().getComponentName());
searchItem = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setSearchableInfo( searchableInfo);
produced following error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setSearchableInfo (android.app.SearchableInfo)' on a null object reference
After i changed in menu.xml android:actionViewClass to app:actionViewClass the problem did not occur again.
menu.xml :
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="...">
<item
android:id="#+id/menu_search"
android:title="#string/menu_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom">
I have implemented SearchView inside one of a Fragment of Tablayout. It is working fine(show/hide) when switching between tablayout fragments.
My issue is that I have a HomeActivity in which I have implemented NavigationDrawer in one of a Fragment I have added TabLayout and in one of TabLayout Fragment I have added SearchView. Issue occurs when I am switching from Fragment which has a SearchView to Fragment from NavDrawer.
Searchview remains up there in other fragments too and when I switch back to that fragment in which I have added searchView then that fragment add one more searchview over Toolbar.
Here's my code from Fragment which as a SearchView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
....
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_search, menu);
LogUtils.LOGI("menu added", "menu");
// Associate searchable configuration with the SearchView
//SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
//SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
//searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
final MenuItem item = menu.findItem(R.id.search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
LogUtils.LOGI("Search filter", query);
final ArrayList<EventModel> filteredModelList = filter(allEventseventsArrayList, query);
allEventsListAdapter.animateTo(filteredModelList);
eventbriteListRecyclerView.scrollToPosition(0);
return true;
}
});
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LogUtils.LOGI("Search", "Search Expands");
titleIconImageView.setVisibility(View.GONE);
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
LogUtils.LOGI("Search", "Search Collapse");
titleIconImageView.setVisibility(View.VISIBLE);
return false;
}
});
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
// Return true to allow the action view to expand
titleIconImageView.setVisibility(View.GONE);
LogUtils.LOGI("Menu", "Menu Expands");
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
// When the action view is collapsed, reset the query
LogUtils.LOGI("Menu", "Menu Collapse");
titleIconImageView.setVisibility(View.VISIBLE);
// Return true to allow the action view to collapse
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
Fragment code in which I don't want SearchView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(false);
....
}
I haven't added any code related to menu in activity.
First run Image with searchView
Image after switching to different fragment from navMenu
Image again switching to fragment which has menu
It's a bit hacky but I solved it by setting setHasOptionsMenu to true and clearing the Menu in onCreateOptionsMenu via
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater){
menu.clear()
}