MaterialSearchView
MaterialSearchView copied to clipboard
How to implement MaterialSearchView in a fragment?
Good evening, I'm try to implement this project in a fragment, but without sucess. Code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_buscar, container, false);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.campo_pesquisa, menu);
MaterialSearchView searchView = (MaterialSearchView) menu.findItem(R.id.barra_pesquisa);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
searchView.setSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewOpened() {
}
@Override
public void onSearchViewClosed() {
}
});
}
Someone can help me please?
You should handle the Search View on the Activity. If your Fragment needs the results you have a few options on how to send it to the fragment, such as:
-
Broadcast the information via
LocalBroadcastManager
-
Send and event using an EventBus.
-
Use a callback method.
I agree with Mauker on the solutions above, but I do think adding support for Fragment use would be beneficial.
Can you explain more why you were unsuccessful in implementing it in your Fragment? What was the issue with the code above?
java.lang.NullPointerException: Attempt to invoke virtual method 'void br.com.mauker.materialsearchview.MaterialSearchView.setOnQueryTextListener(br.com.mauker.materialsearchview.MaterialSearchView$OnQueryTextListener)' on a null object reference
Facing this error while adding in fragment
Is the search view on your fragment layout?
Also, are you sure you're getting its reference once the view is inflated? I couldn't find where are you getting it on the code snippet you provided.
Its a menu item and yes i m taking it reference as u can see in the above mentioned code snippet
Try to find the MSV on your onCreateView
method.
Inside the onCreateOptionsMenu
you'll only have to call searchView.openSearch()
I have used it as a menu item on top of action bar i don't want to use it inside my fragment because i have 3 fragments where i want search so i want it to be a common part of the app