Reset Search in SearchView when you click on back - java

I added Search menu item to filter my list. Everything is working fine with filtering and reset filter.
But I cannot find a way to reset the filter when user click on back button. Actually when user add some text in search field, the first back click will hide the keyboard, and the second click will collapse search field and remove my search text ... but the list still filtered.
What should I do to reset the list?
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
searchMenuItem = menu.findItem(R.id.action_search);
SearchView mSearchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
if (mSearchView != null) {
mSearchView.setIconifiedByDefault(true);
mSearchView.setOnQueryTextListener(this);
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextChange(String s) {
refreshSearch(s);
return false;
}
private void refreshSearch(String s) {
FragmentManager fm = getSupportFragmentManager();
MyListFragment listFragment = (MyListFragment)fm.getFragments().get(0);
MyArrayAdapter arrayAdapter = (MyArrayAdapter)listFragment.getListAdapter();
arrayAdapter.getFilter().filter(s);
}
Edit my question by adding some extra code, that may help to know the reason
#Override
public boolean onQueryTextSubmit(String s) {
hideKeyboard();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
refreshSearch(s);
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
return true;
default:
return false; //return super.onOptionsItemSelected(item);
}
}

I solve the problem by doing this:
searchMenuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
refreshSearch("");
return true;
}
});

You will need to override onBackPressed() in your activity:
#Override
public void onBackPressed() {
if (mSearchView != null && !mSearchView.isIconified()) {
mSearchView.setIconified(true);
} else {
super.onBackPressed();
}
}

searchView should be global variables then you need to do in onQueryTextSubmit method
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchMenuItem = menu.findItem(R.id.app_bar_search);
if (searchMenuItem != null) {
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setFocusable(true);
searchView.setQueryHint("Ara...");
searchView.requestFocusFromTouch();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
searchView.clearFocus();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
adapter.getFilter().filter(s);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
then onBackPressed method
#Override
public void onBackPressed() {
if (!searchView.isIconified() && searchView != null) {
searchView.setIconified(true);
searchView.onActionViewCollapsed();
} else {
super.onBackPressed();
}
}

after a few hours attempt I figured it out.
I'm using support library widgets.
setOnCloseListener for SearchView no longer works, the way you should do it is to use onQueryTextChange in the below code
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
try {
listView.setAdapter(new MyAdapter();
listView.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
#Override
public boolean onQueryTextChange(String s) {
listView.setVisibility(View.GONE);
return false;
}
});
onQueryTextChange is responsible for changes made to your search edittext input. so if you noticed, by default when you press SearchView's back button it clears the text you inputed. well back button will trigger onQueryTextChange cause you changed the text, so if you set visibily of your listview to GONE the problem is fixed
#Override
public boolean onQueryTextChange(String s) {
listView.setVisibility(View.GONE);
return false;
}

Related

want to connect the SearchView to the Mainactivity data - making a notepad app with search view to be connected to notes of notepad

I created a resource menu file i did all the xml work and also added the
` public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
MenuItem item=menu.findItem(R.id.Search);
SearchView searchView=(SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return true;
}`
Now how do I connect my data of notes which is created by user. And once he tries to use the search bar he should be able search among words or notes he has created.
You have to write your search query listener in your
onOptionsItemSelected() instead of OnCreateOptionsMenu like:
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.search_item:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//your logic of search goes here...
searchView.clearFocus(); //disables the keyboard show up on rotation.
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
return true;
}
return super.onOptionsItemSelected(item);
}

How to go previous activity searchview back button?

I have a very simple question. I have implemented searchview in my menu. So the activity starts with expanded searchview. And now when I press back button, the searchview first collapse and goes back to previous activity.
Here's my code
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
searchItem.expandActionView();
SearchView mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
mSearchView.setQueryHint(getString(R.string.search_hint));
mSearchView.setIconifiedByDefault(false);
mSearchView.setFocusable(true);
mSearchView.setIconified(false);
mSearchView.requestFocus();
mSearchView.setGravity(Gravity.END);
mSearchView.setTextDirection(View.TEXT_DIRECTION_RTL);
//mSearchView.setLayoutParams(new Toolbar.LayoutParams(Gravity.END));
//String searchQuery = getIntent().getStringExtra("SEARCH");
//SearchActivity.this.myAdapter.filter(searchQuery);
TextView searchText = mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
//searchText.setText(searchQuery);
Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/font.ttf");
searchText.setTypeface(customFont);
try {
ThaanaUtils.thaanafyTextViewSubclass(searchText, "fonts/faruma.ttf");
}catch (IOException e){
e.printStackTrace();
}
searchText.addTextChangedListener(new ThaanaTextWatcher());
View xIcon = ((View) mSearchView.findViewById(R.id.search_plate));
xIcon.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
SearchActivity.this.myAdapter.filter(newText);
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
onBackPressed();
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_favorites) {
//Intent newActivity = new Intent(SearchActivity.this,FavoritesActivity.class);
//startActivity(newActivity);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed()
{
finish();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
But I don't want to show searchview collapsing when pressed back button. I want to go back to previous activity without collapsing searchview.
How can I achieve that?
Any help is appreciated.
Override the onBackPressed() method in your activity and then put your activity redirection code inside the method. This will solve your problem. Happy coding!
#Override
public void onBackPressed() {
// enter your activity redirection code here.
}
If you didn't call finish() on your previous activity, then just call finish() inside the onBackPressed method. This will destroy the current activity(search activity) and will load previous one. Else you need to go through the usual way by declaring an intent.

Can't set visibility on a SearchView with savedInstanceState

My activity has a menu which includes a SearchView, and I'm setting the SearchView visibility programmatically. I'm using savedInstanceState to preserve the Visibility value eg between rotations, but this aspect is not working: in the scenario where the SearchView visibility is GONE before rotation, the SearchView icon is showing after rotation.
If I debug and evaluate mSearchView.getVisibility() after picking up its value from savedInstanceState, it appears to be correctly set to 8.
There are lines in my code which setVisibility(View.VISIBLE), but none of them are hit between the value from savedInstanceState being set, and the rotated layout appearing to the user.
Layout:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- "Mark Favorite", should appear as action button if possible -->
<item android:id="#+id/action_search"
android:title="#string/action_search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="ifRoom"/>
Activity (onSaveInstanceState):
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
switch (mSearchView.getVisibility()){
case View.VISIBLE:
outState.putInt("SearchViewVisibility",View.VISIBLE);
case View.GONE:
outState.putInt("SearchViewVisibility",View.GONE);
};
}
Activity (Menu setup):
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
//setup SearchView and callbacks
final MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchItem.getActionView();
if(mSavedInstanceState != null){
switch (mSavedInstanceState.getInt("SearchViewVisibility")){
case View.VISIBLE:
mSearchView.setVisibility(View.VISIBLE);
case View.INVISIBLE:
mSearchView.setVisibility(View.INVISIBLE);
case View.GONE:
mSearchView.setVisibility(View.GONE);
}
}
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String query) {
SetFragmentAndFilter(query);
return true;
}
#Override
public boolean onQueryTextChange(String query) {
// check whether this change is clearing all text from the search
if(query.isEmpty()){
// close the searchView
mSearchView.post(new Runnable(){
#Override
public void run(){
mSearchView.clearFocus();
}
});
mSearchView.setIconified(true);
}
//have the list match the new query text
SetFragmentAndFilter(query);
return true;
}
});
return true;
}
Would really appreciate any thoughts!
You should use setVisible method to set the visibility of a menu item.
Change your code to
// Add this property
MenuItem mSearchMenuItem;
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("isVisible", mSearchMenuItem.isVisible());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
//setup SearchView and callbacks
mSearchMenuItem = menu.findItem(R.id.action_search);
if (mSavedInstanceState != null) {
boolean isVisible = mSavedInstanceState.getBoolean("isVisible", true);
mSearchMenuItem.setVisible(isVisible);
}
mSearchView = (SearchView) mSearchMenuItem.getActionView();
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String query) {
// check whether this change is clearing all text from the search
if (query.isEmpty()) {
// close the searchView
mSearchView.post(new Runnable() {
#Override
public void run() {
mSearchView.clearFocus();
}
});
mSearchView.setIconified(true);
}
return true;
}
});
return true;
}

How to make ImageView invisible when multiple clicked (ListView)

I want to hide ImageView when multiple click in Listview.
I did like this:
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
final int checkedCount = listView.getCheckedItemCount();
mode.setTitle(checkedCount + " Selected");
if(checked) {
imageView.setVisibility(View.INVISIBLE);
} else {
imageView.setVisibility(View.VISIBLE);
}
}
#Override
public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
return false;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater menuInflater = mode.getMenuInflater();
menuInflater.inflate(R.menu.toolbar_mode, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
});
But there was only one item invisible and I was getting error.
If anything, I have custom adapter for ListView. Thanks.

onCreateActionMode not being called on GridView long-press?

So I have a GridView that I want to be able to long-press elements to enable a contextual action bar right? I looked up lots of tutorials, including https://www.bignerdranch.com/blog/recyclerview-part-2-choice-modes/ and https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/view/List15.java, as well as others which all state that when using CHOICE_MODE_MULTIPLE_MODAL the MultiChoiceModeListener should automatically be used on a long-press
I see many tutorials using this (and that's it) and it works, but when I long press on elements in my GridView the CAB doesn't start (nor is onCreateActionView called at all) and I absolutely can't figure out why.
Here's my code for the GridView
receiptGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
receiptGridView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
// int count = 0;
ArrayList<Receipt> tmp = new ArrayList();
#Override
public boolean onCreateActionMode(android.view.ActionMode actionMode, Menu menu) {
Log.d("DEBUG","Created action mode!");
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.context_delete, menu);
return true;
}
#Override
public void onItemCheckedStateChanged(android.view.ActionMode actionMode, int i, long l, boolean b) {
receiptGridView.setSelection(i);
Receipt r = (Receipt) listAdapter.getItem(i);
if(b) {
tmp.add(r);
}
else {
tmp.remove(r);
}
actionMode.setTitle("Delete Items");
actionMode.setSubtitle(receiptGridView.getCheckedItemCount() + " items selected.");
}
#Override
public boolean onPrepareActionMode(android.view.ActionMode actionMode, Menu menu) {
return true;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_delete:
removeReceipts(tmp);
actionMode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(android.view.ActionMode actionMode) {
}
});
Turns out to actually trigger the action menu, you have to call setItemChecked on the gridview, so I just did this to my container view on longpress
holder.container.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (ma.mActionMode == null) {
// the line that triggers it
ma.receiptGridView.setItemChecked(position, true);
v.setBackgroundResource(b ? R.color.color_ce5a5a : R.drawable.receipt_item_bg);
view.setBackgroundColor(Color.parseColor("#ce5a5a"));
}
return false;
}
});

Categories

Resources