Add the Search View to the App Bar in Android - android

I am trying to add the search view to the app bar in Android. Followed by this tutorial:http://developer.android.com/training/search/setup.html#add-sv
but when i run the program, it is only a icon could be clicked, the search view did not appear, but the tutorial says it should be appear. Can anyone help me?
menu_main.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/abc_search_hint"
android:icon="#drawable/ic_search_white_48dp"
app:showAsAction="ifRoom|collapseActionView"
android:actionViewClass="android.widget.SearchView" />
</menu>
MainActivity
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
return true;
}
here is the screenshot

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/search"
android:title="#string/search"
android:icon="#drawable/ic_search_white"
android:textColor="#color/white"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.search);
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String queryText) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
if (mSearchTerm == null && newFilter == null) {
return true;
}
if (mSearchTerm != null && mSearchTerm.equals(newFilter)) {
return true;
}
mSearchTerm = newFilter;
mSearchQueryChanged = true;
searchText(newText); //handle this
return true;
}
});
MenuItemCompat.OnActionExpandListener expandListener = new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
return true;
}
};
MenuItemCompat.setOnActionExpandListener(searchItem, expandListener);
return super.onCreateOptionsMenu(menu);
}

Related

Changing background of search bar in toolbar to be white?

I implemented a search bar in my toolbar and it currently looks like this:
But I want to change the background to white with a shadow so that it looks more like this (taken from Material Design guidelines):
How can I do this?
Here is my implementation of the SearchView:
menu_main.xml:
<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"
android:icon="#drawable/ic_search_white_24dp"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="collapseActionView|ifRoom" />
</menu>
MainActivity.java:
public abstract class MainActivity extends AppCompatActivity {
protected Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchActivity.class)));
searchView.setQueryHint("Search");
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
setMenuItemVisibility(menu, searchItem, false);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
supportInvalidateOptionsMenu();
return true;
}
});
return true;
}
private void setMenuItemVisibility(Menu menu, MenuItem searchItem, boolean isVisible) {
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
Log.d(TAG, item.toString());
if (item != searchItem) {
item.setVisible(isVisible);
}
}
}
}
How can I style the SearchView to change the background color?

How to add search and checkbox icon with their functions in android action bar?

I want to add a searchview and checkbox into action bar menu. And this checkbox will be visible if searchview is opened. And in it's opposite case it will be hidden. How I can do this?
I do something below . But it doesnt work correctly. I want hide checkbox (In my notes) when searchview is closed.
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/search_button"
android:icon="#drawable/ic_icon_search"
android:title="Arama"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView">
</item>
<item
android:id="#+id/search_in_my_notes_checkbox"
app:showAsAction="ifRoom"
android:title="#string/search_in_my_notes"
android:checkable="true"
android:visible="false"
/>
</menu>
HomeActivity.java
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.search_button){
MenuItem searchInMyNotesCheckbox = (MenuItem)menu.findItem(R.id.search_in_my_notes_checkbox);
searchInMyNotesCheckbox.setVisible(true);
}
return super.onOptionsItemSelected(item);
}
I found an alternative solution. I will use two checkbox image with checked and unchecked. And I will override onCreateOptionsMenu like this :
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
this.menu = menu;
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem search = (MenuItem)menu.findItem(R.id.search_button2);
final MenuItem searchInMyNotesCheckbox = (MenuItem) menu.findItem(R.id.search_in_my_notes_checkbox);
MenuItemCompat.setOnActionExpandListener(search,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
// Return true to allow the action view to expand
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
MenuItem searchInMyNotesCheckbox = (MenuItem) menu.findItem(R.id.search_in_my_notes_checkbox);
searchInMyNotesCheckbox.setVisible(false);
return true;
}
});
searchInMyNotesCheckbox.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if(item.getIcon() == R.drawable.checked_checkbox){
item.setIcon(R.drawable.unchecked_checkbox);
}
else {
item.setIcon(R.drawable.checked_checkbox);
}
return false;
}
});
return super.onCreateOptionsMenu(menu);
}

Adding SearchView in Fragment

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">

How can i get the text entered in search in action bar to a string?

I have an activity that shows search in title bar perfectly, but right now i want to get the text entered in search in action bar to a string. Please help !
Her is my menu/xml
<?xml version="1.0" encoding="utf-8"?>
<item android:id="#+id/action_search"
android:title="Search"
android:icon="#android:drawable/ic_menu_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView"
/>
</menu>
Her is the code in onCreate
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Have you used searchView? You can use following code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search)
.getActionView();
if (null != searchView) {
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
// This is your adapter that will be filtered
return true;
}
public boolean onQueryTextSubmit(String query) {
// **Here you can get the value "query" which is entered in the search box.**
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
If you are using a Toolbar you can do this:
MenuItem menuItem = getToolbar().getMenu().findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Log.i("well", " this worked");
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.i("well", " this worked");
return false;
}
});

How to use SearchView in Toolbar Android

The code on which I am working, is using a Toolbar and inflating a menu.
Here is the code
private Toolbar mToolbar;
mToolbar.inflateMenu(R.menu.chat_screen_menu);
setupMenu ();
private void setupMenu ()
{
mMenu = mToolbar.getMenu();
if (mMenu != null)
{
if (mChatPager != null && mChatPager.getCurrentItem() > 0)
{
mMenu.setGroupVisible(R.id.menu_group_chats, true);
mMenu.setGroupVisible(R.id.menu_group_contacts, false);
}
else
{
mMenu.setGroupVisible(R.id.menu_group_chats, false);
mMenu.setGroupVisible(R.id.menu_group_contacts, true);
mMenu.setGroupVisible(R.id.menu_group_otr_verified,false);
mMenu.setGroupVisible(R.id.menu_group_otr_unverified,false);
mMenu.setGroupVisible(R.id.menu_group_otr_off,false);
}
}
mToolbar.setOnMenuItemClickListener(new OnMenuItemClickListener ()
{
..........
}
}
But now, they require a Search button in the tool_bar.
I managed to put it, I followed a guide here
When I try to write something to search, the toast I had put to test the listener never shown.
which indicates listener is not working
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.chat_screen_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_menu_search));
final Toast toast = new Toast(mApp);
if (mSearchView != null )
{
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener()
{
public boolean onQueryTextChange(String newText)
{
mSearchString = newText;
//doFilterAsync(mSearchString);
toast.makeText(getApplicationContext(), "Test1", Toast.LENGTH_LONG).show();
return true;
}
public boolean onQueryTextSubmit(String query)
{
mSearchString = query;
//doFilterAsync(mSearchString);
toast.makeText(getApplicationContext(), "Test2", Toast.LENGTH_LONG).show();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
}
return true;
}
You have to use Appcompat library for that. Which is used like below:
dashboard.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:title="Search"/>
</menu>
Activity file (in Java):
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.dashboard, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = null;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
}
return super.onCreateOptionsMenu(menu);
}
Activity file (in Kotlin):
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_search, menu)
val searchItem: MenuItem? = menu?.findItem(R.id.action_search)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView: SearchView? = searchItem?.actionView as SearchView
searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
return super.onCreateOptionsMenu(menu)
}
manifest file:
<meta-data
android:name="android.app.default_searchable"
android:value="com.apkgetter.SearchResultsActivity" />
<activity
android:name="com.apkgetter.SearchResultsActivity"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
searchable xml file:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/search_hint"
android:label="#string/app_name" />
And at last, your SearchResultsActivity class code. for showing result of your search.
If you would like to setup the search facility inside your Fragment, just add these few lines:
Step 1 - Add the search field to you toolbar:
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="Search"/>
Step 2 - Add the logic to your onCreateOptionsMenu()
import android.support.v7.widget.SearchView; // not the default !
#Override
public boolean onCreateOptionsMenu( Menu menu) {
getMenuInflater().inflate( R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
searchView = (SearchView) myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// Toast like print
UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
if( ! searchView.isIconified()) {
searchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
// UserFeedback.show( "SearchOnQueryTextChanged: " + s);
return false;
}
});
return true;
}
If you want to add it directly in the toolbar.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:id="#+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Search"
android:layout_centerHorizontal="true" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
Integrating SearchView with RecyclerView
1) Add SearchView Item in Menu
SearchView can be added as actionView in menu using
app:useActionClass = "android.support.v7.widget.SearchView"
.
<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="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="#+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
2) Implement SearchView.OnQueryTextListener in your Activity
SearchView.OnQueryTextListener has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
3) Set up SerchView Hint text, listener etc
#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.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
4) Implement SearchView.OnQueryTextListener
This is how you can implement abstract methods of the listener.
#Override
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
5) Write a filter method in your RecyclerView Adapter.
You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView.
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App
Implementing the SearchView without the use of the menu.xml file and open through button
In your Activity we need to use the method of the onCreateOptionsMenumethod in which we will programmatically inflate the SearchView
private MenuItem searchMenu;
private String mSearchString="";
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
mSearchView.setMaxWidth(Integer.MAX_VALUE);
searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
assert searchManager != null;
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
mSearchString = newText;
return true;
}
public boolean onQueryTextSubmit(String query) {
mSearchString = query;
searchMenu.collapseActionView();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
return true;
}
And in your Activity class, you can open the SearchView on any button click on toolbar like below
YOUR_BUTTON.setOnClickListener(view -> {
searchMenu.expandActionView();
});
I search and implement so much code but that not worked for me .
Then I implement custom toolbar into my XML file and then inside toolbar tag I use searchview tag.
Hope it work for you.

Categories

Resources