I have a collapsible search box. I want to capture the text change event and perform a search on a list. But I am not able to capture the onTextChanged event.
Menu Resource:
<item android:id="#+id/action_search"
android:icon="#drawable/abs__ic_search"
android:title="Search"
android:showAsAction="always"
android:iconifiedByDefault="false"
android:actionViewClass="com.actionbarsherlock.widget.SearchView"/>
Activity:
import com.actionbarsherlock.view.MenuItem;
public class FromPageActivity extends SherlockListActivity {
EditText search;
//more code here
.
.
.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
search(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void search(MenuItem item){
search = (EditText) item.getActionView();
search.addTextChangedListener(filterTextWatcher);
search.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
private TextWatcher filterTextWatcher = new TextWatcher(){
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
Toast.makeText(FromPageActivity.this, "changed", Toast.LENGTH_LONG).show();
}
};
}
What am I missing out?
Try to use com.actionbarsherlock.view.MenuItem instead of MenuItem as parameter in search and onOptionMenuItemSelected methods
Also you can try to use SearchView.OnQueryTextListener to detect text changing, for example:
public boolean onCreateOptionsMenu(Menu menu)
{
getSupportMenuInflater().inflate(R.menu.menu, 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
adapter.getFilter().filter(newText);
return true;
}
public boolean onQueryTextSubmit(String query)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(query);
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
Related
I have implemented SearchView in ActionBar, But the problem with it is, whenever am typing something and press submit, the SearchView doesn't collapse back into that Search icon, it stays expanded, neither when I press Back button, SearchView doesn't collapse back.
My implementation is like this:
menu_search.xml
<item
android:id="#+id/app_bar_search"
android:icon="#drawable/ic_search_white_24dp"
android:title="Search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always" />
MainActivity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
item = menu.findItem(R.id.app_bar_search);
searchView = (SearchView) item.getActionView();
searchView.setMaxWidth(Integer.MAX_VALUE);
int searchBarId = searchView.getContext().getResources().getIdentifier("android:id/search_bar", null, null);
searchBar = searchView.findViewById(searchBarId);
searchBar.setLayoutTransition(new LayoutTransition());
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
item.collapseActionView();
searchView.setQuery("", false);
searchView.clearFocus();
searchBar.clearFocus();
.
.
.
.
.
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
Things I have tried:
#Override
public void onBackPressed() {
super.onBackPressed();
if (item.isActionViewExpanded()) {
item.collapseActionView();
} else {
super.onBackPressed();
}
}
and
#Override
public void onBackPressed() {
super.onBackPressed();
if (searchView != null) {
searchView.onActionViewCollapsed();
searchView.setQuery("", false);
searchView.clearFocus();
searchBar.clearFocus();
hideSoftKeyboard(MainActivity.this);
} else {
super.onBackPressed();
}
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
SearchView expands from left to right to type but doesn't collapse back form right to left.
Please advice.
Try below code and let me know if it works.
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, ResultActivity.class)));
searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
#Override
public boolean onSuggestionSelect(int position) {
return false;
}
#Override
public boolean onSuggestionClick(int position) {
searchView.clearFocus();
item.collapseActionView();
return false;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
searchView.clearFocus();
item.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
I was going through the second page of Google search and found this.
It worked for me.
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
searchView.setIconified(true);
}
}
});
There is a searchview in menu and i have a button. When the button is clicked i need the searchview to open for search which means focus should be on searchview for enter search texts.
#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_fooddoof, menu);
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.search));
TextView searchText = (TextView)
searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/ProximaNovaRgRegular.ttf");
searchText.setTypeface(myCustomFont);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent intent = new Intent(descStore.this, listdisplay.class);
intent.putExtra("deskey", query);
startActivity(intent);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//android.widget.Filter filter = descAdapter.getFilter();
//filter.filter(newText);
return true;
}
});
searchView.setSubmitButtonEnabled(true);
return true;
}
When click a button:
#Override
public void onClick(View v) {
if (v == mViews.description1) {
searchview.seticonified(false);
}
}
I've tried seticonified option but it is not working . Please help.
You could request the focus of the searchview as below
#Override
public void onClick(View v) {
switch (view.getId()) {
case R.id.your_button_id:
searchview.seticonified(false);
searchview.requestFocus(); //request focus of the view
break;
}
}
I am using searchview in my application ( without action bar). How can I collapse searchview after query text submit?
I have these listeners ;
#Override
public boolean onQueryTextSubmit(String query) {
InputMethodManager imm = (InputMethodManager)thisFr.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(globalSearch.getWindowToken(), 0);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
I don't use ActionBar so I don't have a function like collapseActionView().
you need to call setIconified(true) twice to actually collapse your search view, with first call text is cleared with second call keyboard and search view get closed.
You can do it this way in your activity, tested with actionbarsherlock (it even hides the keyboard, make sure to return false in onQueryTextSubmit):
private MenuItem searchMenuItem;
public MenuItem getSearchMenuItem() {
return searchMenuItem;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// ...
searchMenuItem = menu.findItem(R.id.menu_search);
// ...
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
MenuItem searchMenuItem = getSearchMenuItem();
if (searchMenuItem != null) {
searchMenuItem.collapseActionView();
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// ...
return true;
}
});
// ...
return super.onCreateOptionsMenu(menu);
}
If you are using the SearchView in the OptionsMenu, you ca call invalidateOptionsMenu()
//close suggestion list on query text submit
searchView.setIconified(true);
final MenuItem searchterm = menu.findItem(R.id.search);
SearchView searchView = null;
searchView = (SearchView) searchterm.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
searchterm.collapseActionView();
}});
I am using SearchView and it is working fine but only setOnCloseListener is not working; Here is my code
import com.actionbarsherlock.widget.SearchView.OnCloseListener;
and
searchView.setOnCloseListener(new OnCloseListener() {
#Override
public boolean onClose() {
Toast.makeText(context, "close", Toast.LENGTH_SHORT).show();
return false;
}
});
**EDIT****
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Used to put dark icons on light action bar
//Create the search view
final SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setQueryHint("Search");
searchView.setIconifiedByDefault(true);
//search button
menu.add(Menu.NONE,Menu.NONE,1,"Search a word")
.setIcon(R.drawable.abs__ic_search_api_holo_light)
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
MenuItem sView = menu.findItem(1);
sView.setOnActionExpandListener(this);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
adopter.getFilter().filter(null);
Toast.makeText(getApplicationContext(), "collapse", Toast.LENGTH_LONG).show();
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(getApplicationContext(), "Expand", Toast.LENGTH_LONG).show();
return true; // Return true to expand action view
}
Solved it by myself. Just leave setOnCloseListener it will not work, and put following code in onCreateOptionsMenu
// searchView.setOnCloseListener(new OnCloseListener() {
// #Override
// public boolean onClose() {
// adapter.getFilter().filter("");
// Toast.makeText(getBaseContext(), "on close", Toast.LENGTH_SHORT).show();
// return false;
// }
// });
MenuItem menuItem = menu.findItem(ID_OF_SEARCHVIEW);
menuItem.setOnActionExpandListener(new OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
adapter.getFilter().filter("");
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
adapter.getFilter().filter("");
return true;
}
});
I have encountered the same problem with onCloseListener not invoking for the SearchView.
Understand from the bug issue raised in 25758, and some postings I have read, to invoke onCloseListener, you need to set:
searchView.setIconifiedByDefault(true);
But for my case I wanted to have the search view opened & not iconified all the time. I manage to resolve this by adding one more line below:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_bar, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(queryTextListener);
searchView.setIconifiedByDefault(true);
searchView.setIconified(false);
return true;
}
The searchView.setIconified(false) will cause the searchView to open up, despite setting the default to iconified to true in the previous line. In this way, I managed to have both a SearchView
that opens up all the time & having it invoke the onCloseListener.
I'm using this code. And it works perfectly
#Override
public void onStartSearch() {
}
#Override
public void onSearch(String search) {
}
#Override
public void onCloseSearch() {
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.your_menu, menu);
// Associate searchable configuration with the SearchView
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem); //here I user appcompat, but you can take it just from actionbarsherlock
SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchAutoComplete.setTextColor(getResources().getColor(R.color.action_bar_text_color));
mSearchView.setIconifiedByDefault(true);
mSearchView.setSubmitButtonEnabled(false);
/**
* Set all of different kinds of listeners
*/
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
menuIsOpen = false;
onCloseSearch();
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
menuIsOpen = true;
onStartSearch();
return true;
}
});
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String s) {
onSearch(s);
return false;
}
#Override
public boolean onQueryTextSubmit(String s) {
onSearch(s);
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
/**
* Function for closing search when android is less than 14
*/
public boolean onBackButton() {
if (AndroidUtils.getSdkVersion() >= 14)
return false;
if (menuIsOpen) {
menuIsOpen = false;
getActivity().supportInvalidateOptionsMenu();
onCloseSearch();
return true;
}
return false;
}
After backButton it close search, or just by selecting close from action bar.
You can use a OnActionExpandListener:
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
SearchView searchView = new SearchView(((SherlockFragmentActivity) getActivity()).getSupportActionBar().getThemedContext());
searchView.setIconifiedByDefault(true);
// ...
MenuItem menuItem = menu.add(R.string.search);
// ...
menuItem.setOnActionExpandListener(this);
}
#Override
public boolean onMenuItemActionExpand(final MenuItem item) {
mInSearchMode = true;
return true;
}
#Override
public boolean onMenuItemActionCollapse(final MenuItem item) {
mInSearchMode = false;
return true;
}
I tried to get Search box to work on Action Bar Sherlock.
This is my PreLocationActivity:
#ContentView(R.layout.search)
public class PreLocationActivity extends RoboSherlockActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.map_layout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Used to put dark icons on light action bar
menu.add("Search")
.setIcon(R.drawable.ic_search_inverse)
.setActionView(R.layout.collapsible_edittext)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
#Override
public boolean onSearchRequested() {
return super.onSearchRequested();
}
}
This is my SearchableActivity:
#ContentView(R.layout.search)
public class SearchableActivity extends RoboSherlockFragmentActivity {
#InjectView(R.id.addressListView) ListView addressView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doGeoSearch(query);
}
}
public void doGeoSearch(String query){
Geocoder geocoder;
ArrayList<Address> addresses;
ArrayList<String> address = new ArrayList<String>() ;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = (ArrayList<Address>) geocoder.getFromLocationName(query, 6);
Log.d("Address",String.valueOf(addresses));
for(int i = 0;i<addresses.size();i++)
{
String addr = new String();
addr.concat(addresses.get(i).getAddressLine(0));
addr.concat(addresses.get(i).getAddressLine(1));
addr = addresses.get(i).getAddressLine(0) + addresses.get(i).getLocality() + addresses.get(i).getAdminArea();
//addr.concat(addresses.get(i).getAddressLine(2));
Log.d("addr",addr);
address.add(addr);
}
SearchAddressAdapater addressList = new SearchAddressAdapater(getApplicationContext(),R.layout.search_list,addresses, SearchableActivity.this);
addressView.setAdapter(addressList);
//ListView addressListView = new ListView();
} catch (IOException e) {
//Handle exception
}
}
No success at all. As in, when I type something on the Prelocation Activity and press enter, nothing is being searched. Do I have to treat it as an EditText and write a text listener for that which then calls the geoCoder and gets me the locations or is there a smarter way to go about it?
Android Support Library(v4 + v7):
Support Library v7: http://developer.android.com/tools/support-library/features.html#v7-appcompat
Google now supports the ActionBar compatibility back to Android 2.1(API 7).
It is easy to make the transition because the method names are the same and/or very similar.
Add the Support Library with Resources: http://developer.android.com/tools/support-library/setup.html#libs-with-res
Your Manifest: AndroidManifest.xml
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
Your Menu: menu.xml
<item
android:id="#+id/menu_search"
android:actionViewClass="android.support.v7.widget.SearchView"
android:icon="#drawable/ic_action_search"
android:showAsAction="ifRoom|collapseActionView"
android:title="Search"/>
ActionBarSherlock [deprecated, use appcompat]:
Here is how to use the standard SearchView and SearchManager in Android with ActionBarSherlock! I am using this code and works fine. I have tested this on Android 2.3(API 10) - Android 4.3(API 18).
Great Tutorial and Documentation:
http://developer.samsung.com/android/technical-docs/UI-unification-with-older-Android-versions-using-ActionBarSherlock
Keep in mind:
Custom Search with ActionBarSherlock(min. API 7)
SearchView with ActionBarSherlock(min. API 8)
Your Menu: menu.xml
<item
android:id="#+id/menu_search"
android:actionViewClass="com.actionbarsherlock.widget.SearchView"
android:icon="#drawable/ic_action_search"
android:showAsAction="ifRoom|collapseActionView"
android:title="Search"/>
For Both:
Your Activity: MainActivity.java
public boolean onCreateOptionsMenu(Menu menu)
{
getSupportMenuInflater().inflate(R.menu.menu, 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
adapter.getFilter().filter(newText);
return true;
}
public boolean onQueryTextSubmit(String query)
{
// this is your adapter that will be filtered
adapter.getFilter().filter(query);
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
Let me know if this works for you as well and let me know if you need anymore help!
private EditText search;
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu)
{
menu.add(0, 1, 1, R.string.menu_search).setIcon(R.drawable.ic_action_search).setActionView(R.layout.action_search).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item)
{
switch (item.getItemId())
{
case 1:
search = (EditText) item.getActionView();
search.addTextChangedListener(filterTextWatcher);
search.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
private TextWatcher filterTextWatcher = new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// your search logic here
}
};
A similar question there are here where I had the problem to assign the adapter.
How to implement search widget with a listview using SherlockActionbar?
I hope that it would help because I had the same problem.
To use the adapter the best way is that the class implements SearchView.OnQueryTextListener and then you donĀ“t have to create the inner class and you will have the adapter.
In your code will be something as:
public class MainActivity extends SherlockListActivity implements SearchView.OnQueryTextListener
and then in the class you have to define the methods. The adapter will be the adapter that you have in your class ArrayAdapter adapter. But you should define it as private in the class.
public boolean onQueryTextChange(String newText) {
// this is your adapter that will be filtered
adapter.getFilter().filter(newText);
return true;
}
public boolean onQueryTextSubmit(String query) {
// this is your adapter that will be filtered
adapter.getFilter().filter(query);
return true;
}
In the line where you are setting:
searchView.setOnQueryTextListener(queryTextListener);
Should be:
searchView.setOnQueryTextListener(this);
If you have any problem let me know, I was with a similar problem today and read your question without answer.