searchview not gain focus but keyboard opens - android

i m using searchview for search functionality my problem is that when i click on search icon keyboard gets opened but searchview does not get focus below is my code
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/send_invitation"
android:icon="#drawable/send_icon_invite_participant"
android:orderInCategory="93"
android:title="#string/invitation"
app:showAsAction="always">
</item>
<item
android:id="#+id/search"
android:orderInCategory="100"
app:actionViewClass="android.support.v7.widget.SearchView"
android:icon="#drawable/search_icn"
android:title="#string/search"
app:showAsAction="always"/>
</menu>
below is code from method
#Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.invite_participant, menu);
final MenuItem searchItem = menu.findItem(R.id.search);
SearchManager searchManager = (SearchManager) activity.getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setTextColor(getResources().getColor(R.color.colorAccent));
searchEditText.setHintTextColor(getResources().getColor(R.color.colorAccent));
searchItem.expandActionView();
ImageView searchIcon = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_button);
searchIcon.setImageResource(R.drawable.search_icn);
ImageView searchCloseIcon = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
searchCloseIcon.setImageResource(R.drawable.reject_icon_notification);
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(activity.getComponentName()));
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setItemsVisibility(menu, searchItem, false);
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (adapter != null) {
adapter.fliter(newText);
}
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
setItemsVisibility(menu, searchItem, true);
return false;
}
});
}
}
private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
for (int i=0; i<menu.size(); ++i) {
MenuItem item = menu.getItem(i);
if (item != exception) item.setVisible(visible);
}
}
i m not able to find why it does not get focused please help me in finding where i have done mistake any help is appreciated.

You can add these lines for focus with searchview.
searchView.setFocusable(true);
searchView.requestFocus();
searchView.requestFocusFromTouch();
If it'll not work then First expand search view then request for focus.

You can achieve it either by adding below code in your Activity's onCreate method.
getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
or by adding this line in your AndroidManifest file
android:windowSoftInputMode="stateHidden"
Edit:
Try something like this
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

Related

using SearchView with toolbar, How to open keyboard when activity loads?

I have tried the other possible answer provided in stackoverflow but none of them is working so I am posting it here again.
The problem is I want to open the softkeyboard automatically when the activity opens, but none of the ways I have tried is working.
My Activity code where I am setting SearchView:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) SelectCityActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = null;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(SelectCityActivity.this.getComponentName()));
searchView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
searchView.setQueryHint(searchHint);
searchView.setIconifiedByDefault(false);
final SearchView finalSearchView = searchView;
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
showInputMethod(view);
finalSearchView.onActionViewExpanded();
}
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String s) {
valueAdapter.getFilter().filter(Methods.capitalize(s));
return true;
}
});
}
return true;
}
And menu xml file:
<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="#android:drawable/ic_menu_search"
android:title="#string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
</menu>
Just call this line in your code
searchView.requestFocus();
That's it.
Put below code on onCreate of Activity:
((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
Hope this will help you.
try this to force open soft keyboard:
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

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;
}
});

MenuItemCompat.setOnActionExpandListener doesn't do anything

Background
I have a searchView being initialized using a special class I've made, that's being used across all of the activities and fragments.
The problem
Recently, probably due to updates to the support library (or because I didn't use it so far, I don't remember), I can't catch events of expand/collapse of the searchView.
As I've found, this happens even if I use setSupportActionBar with a Toolbar instance.
What I've tried
I've tried using each of the next methods, but none worked:
MenuItemCompat.setOnActionExpandListener.
MenuItemCompat.setOnActionExpandListener together with iconifying the SearchView, as suggested on some websites.
setOnActionExpandListener on the search menu item itself, but then it crashes since it can't be used when extending the ActionBarActivity.
SearchView.setOnCloseListener , but this works only if I close it, and only using the UI (doesn't get called when calling collapseActionView ).
I've also tried to mess around with the XML file of the search menu item.
The code
Here's the helper class I've made:
SearchHolderCompat
public class SearchHolderCompat {
public MenuItem mSearchMenuItem;
public SearchView mSearchView;
private final Activity _context;
public SearchHolderCompat(final Activity context) {
_context = context;
}
public boolean isCurrentyExpanded() {
return mSearchMenuItem != null && MenuItemCompat.isActionViewExpanded(mSearchMenuItem);
}
public boolean hasQuery() {
return mSearchMenuItem != null && mSearchView != null && MenuItemCompat.isActionViewExpanded(mSearchMenuItem)
&& !TextUtils.isEmpty(mSearchView.getQuery());
}
public void addSearchItemAndInit(final Menu menu, final OnQueryTextListener onQueryTextListener,
final OnActionExpandListener onActionExpandListener) {
final MenuInflater menuInflater = _context.getMenuInflater();
menuInflater.inflate(R.menu.search_menu_item, menu);
init(menu.findItem(R.id.menuItem_search), onQueryTextListener, onActionExpandListener);
}
public void init(final MenuItem searchMenuItem, final OnQueryTextListener onQueryTextListener,
final OnActionExpandListener onActionExpandListener) {
this.mSearchMenuItem = searchMenuItem;
mSearchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
if (mSearchView == null) {
MenuItemCompat.setShowAsAction(searchMenuItem, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
| MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
MenuItemCompat.setActionView(searchMenuItem, mSearchView = new SearchView(_context));
}
mSearchView.setQueryHint(_context.getString(R.string.search));
mSearchView.setOnQueryTextListener(onQueryTextListener);
MenuItemCompat.setOnActionExpandListener(searchMenuItem, onActionExpandListener);
}
}
MainActivity.java
public class MainActivity extends ActionBarActivity {
SearchHolderCompat mSearchHolder = new SearchHolderCompat(this);
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
mSearchHolder.addSearchItemAndInit(menu, new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(final String arg0) {
android.util.Log.d("AppLog", "onQueryTextSubmit");
return false;
}
#Override
public boolean onQueryTextChange(final String queryText) {
android.util.Log.d("AppLog", "onQueryTextChange");
return true;
}
}, new OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(final MenuItem arg0) {
android.util.Log.d("AppLog", "onMenuItemActionExpand");
return false;
}
#Override
public boolean onMenuItemActionCollapse(final MenuItem arg0) {
android.util.Log.d("AppLog", "onMenuItemActionCollapse");
return false;
}
});
return true;
}
}
search_menu_item.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" >
<!-- search items -->
<item
android:id="#+id/menuItem_search"
android:icon="#drawable/ic_action_search"
android:title="#string/search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"
tools:ignore="AlwaysShowAction"/>
</menu>
The question
What's the correct way to handle the SearchView and the search menu item (using the support library) ?
How come "MenuItemCompat.setOnActionExpandListener" doesn't work?
After looking for a solution for couple of hours I've implement something like this. and worked for me. (I wanted Expand and Collapse events anyhow)
.
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
if(searchItem != null)
{
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
// use this method for search process
searchView.setOnSearchClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Search view is expanded
showSearchPage();
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener()
{
#Override
public boolean onClose()
{
//Search View is collapsed
hideSearchPage();
return false;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String query)
{
// use this method when query submitted
Toast.makeText(MainActivity.this, query, Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String newText)
{
// use this method for auto complete search process
Log.e("SearchValueIs",":"+newText);
return false;
}
});
}
return super.onCreateOptionsMenu(menu);
}
Hope It will help Someone...
Android training
app:showAsAction="ifRoom|collapseActionView"
You can add ViewTreeObserver to track the visibility state of android.support.v7.appcompat.R.id.search_edit_frame. You can check my answer here: https://stackoverflow.com/a/28762632/1633609
You can see below how to handle Expand and Collapsed states!
To answer why MenuItemCompat.setOnActionExpandListener(...) is not working, this listener is only called if the showAsAction of the SearchView is set to MenuItemCompat.SHOW_AS_ACTION_ALWAYS (you can also add more options).
This is the copy of my answer form the other question:
I found that MenuItemCompat.setOnActionExpandListener(...) is not working if you don't pass:
searchItem
.setShowAsAction(MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
| MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
But this is changing the SearchView and is replacing the DrawerToggle with back arrow.
I wanted to keep the original views and still track the Expanded/Collapsed state and use supported Search View.
Solution:
When android.support.v7.widget.SearchView is changing the view state the LinearLayout view's, with id android.support.v7.appcompat.R.id.search_edit_frame, visibility value is being changed from View.VISIBLE to View.GONE and opposite. So I add ViewTreeObserver to track the visibility change of the search edit frame.
menu_search.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:icon="#android:drawable/ic_menu_search"
android:title="#string/search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"/>
</menu>
In the activity:
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
..........
private View mSearchEditFrame;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = (MenuItem) menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat
.getActionView(searchItem);
searchView.setSubmitButtonEnabled(false);
mSearchEditFrame = searchView
.findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
int oldVisibility = -1;
#Override
public void onGlobalLayout() {
int currentVisibility = mSearchEditFrame.getVisibility();
if (currentVisibility != oldVisibility) {
if (currentVisibility == View.VISIBLE) {
Log.v(TAG, "EXPANDED");
} else {
Log.v(TAG, "COLLAPSED");
}
oldVisibility = currentVisibility;
}
}
});
return super.onCreateOptionsMenu(menu);
}
I know I'm very late to post this answer but hope it helps someone else. I recently came across the issue and I just made the Override methods return true and it worked like a charm.
#Override
public boolean onMenuItemActionExpand(final MenuItem arg0) {
android.util.Log.d("AppLog", "onMenuItemActionExpand");
return true;
}
#Override
public boolean onMenuItemActionCollapse(final MenuItem arg0) {
android.util.Log.d("AppLog", "onMenuItemActionCollapse");
return true;
}
In more recent versions
menuSearch.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
//SearchView appers
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
//SearchView disappears
return true;
}
});

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.

Auto Collapse ActionBar SearchView on Soft Keyboard close

I am currently using an ActionBar menu item to display a SearchView in the action bar. When the search menu item is expanded the soft keyboard is displayed which is what I want. Now, when the user presses the back button to close the soft keyboard, I would also like to collapse the SearchView in the action bar.
I have tried implementing the following listeners OnKeyListener and OnFocusChangeListener on the MenuItem and the ActionView. I have also tried using OnBackPressed() in the Activity. None of the above detect when the back button is used to close the soft keyboard.
Any ideas?
I have implemented OnActionExpandListener to know when the SearchView is visible.
I'll expand on #user1258568 's answer for the lazy. This worked for me. Note that it clears your query when focus is lost.
final MenuItem searchMenuItem = optionsMenu.findItem(R.id.search);
final SearchView searchView = (SearchView) searchMenuItem.getActionView();
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean queryTextFocused) {
if(!queryTextFocused) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}
}
});
I found a better solution.
searchView.setOnQueryTextFocusChangeListener().
The OnQueryTextFocusChangeListener gets called when the keyboard is displayed or hidden. Gets called first when the keyboard is displayed and the search view will have focus. Gets called again when keyboard is hidden and search view will lose focus, can close search viewthen using
menuItem.collapseActionView().
Just Override onBackPressed like this:
#Override
public void onBackPressed() {
if (searchView.isShown()){
searchView.onActionViewCollapsed(); //collapse your ActionView
searchView.setQuery("",false); //clears your query without submit
isClosed = true; //needed to handle closed by back
} else{
super.onBackPressed();
}
}
and your onCreateOptionsMenu would inflate the mSearchView like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_search, menu);
mSearchView = (SearchView) menu.findItem(R.id.menu_action_search).getActionView();
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnSearchClickListener(this);
mSearchView.setOnCloseListener(this);
isClosed = true;
return true;
}
have you class implement the following like this:
public class myActivity extends FragmentActivity implements
SearchView.OnQueryTextListener, View.OnClickListener, SearchView.OnCloseListener {
which you will also need:
#Override
public void onClick(View view) {
isClosed = false;
}
#Override
public boolean onClose() {
isClosed = true;
return false;
}
You will need to make "mSearchView" and "isClosed" both global variables to the activity.
The answer from Jon Willis works great. This is an improvement to his answer.
First, create a new class that implements View.OnFocusChangeListener:
public class SearchViewFocusListener implements View.OnFocusChangeListener {
private final MenuItem mMenuItem;
public SearchViewFocusListener(MenuItem menuItem) {
mMenuItem = menuItem;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
mMenuItem.collapseActionView();
if (v instanceof SearchView) {
((SearchView) v).setQuery("", false);
}
}
}
}
Next, set the listener on your SearchView:
searchView.setOnQueryTextFocusChangeListener(new SearchViewFocusListener(menuItem));
You only need to put the "collapseActionView" attribute in the menu layout
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_item_search"
android:title="#string/search"
android:iconifiedByDefault="true"
android:icon="#drawable/ic_action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"/> <--this one
</menu>
That will give you the functionality you look for all by itself.Don't forget to call the method "clearFocus" on the SearchView to close the keyboard once you send the query.
This is what I did for making the keyboard disappear. You can try to see if this works for you. I set the searchView to invisible and then to visible again.
//set query change listener
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
/**
* hides and then unhides search tab to make sure keyboard disappears when query is submitted
*/
searchView.setVisibility(View.INVISIBLE);
searchView.setVisibility(View.VISIBLE);
return false;
}
});
It's achievable like this:
private void setupSearchView(Menu menu) {
final MenuItem searchMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) searchMenuItem.getActionView();
[...]
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
searchMenuItem.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
}
Solutions based on setOnQueryTextFocusChangeListener() did not work for me because the event was not launched - the searchView did not lose focus when submitted, probably because I perform the search in the same activity that contains the Search View.
Anyway, I think using OnQueryTextListener is more correct, as it describes the event of submitting text more precisely.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.home_screen, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
final SearchView searchView = (SearchView) searchMenuItem
.getActionView();
searchView.setIconifiedByDefault(false);
if (searchManager != null && searchView != null) {
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView
.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if (searchMenuItem != null) {
searchMenuItem.collapseActionView();
}// end if
if (searchView != null) {
searchView.setQuery("", false);
}// end if
}// end if
}
});
searchView
.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
/**
* hides and then unhides search tab to make sure
* keyboard disappears when query is submitted
*/
if (searchView != null) {
searchView.setVisibility(View.INVISIBLE);
searchView.setVisibility(View.VISIBLE);
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
});
}
return super.onCreateOptionsMenu(menu);
}
If you want to collapse keyboard when user clicks search icon on keyboard
this can be achieved by simple
inside onquerytextsubmitted {
searchView.clearfocus()
}
You need to call setIconified twice.
To actually collapse your search view and close the keyboard.
With first call text of search view is cleared with second call keyboard and search view get closed.
For some reason, menuItem.collapseActionView() did not work so I used searchView.setIconified(true) instead.
This gives the below result as the code sample.
final MenuItem searchItem = (MenuItem) menu.findItem(R.id.menu_item_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextFocusChangeListener(new SearchView.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
searchView.setIconified(true);
}
}
});

Categories

Resources