Android SearchView - empty query doesn't work - android

I'm trying to add recent searches to the SearchView on a toolbar:
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (s!= null )
{
if (s.isEmpty()){
loadRecentList();
}
else{
search(s);
}
}
return true;
}
});
The search is working fine, but I can't see the recent list results.
I found this Android SearchView.OnQueryTextListener OnQueryTextSubmit not fired on empty query string
but modifying the ActionBar library is not a nice solution.
Does anyone have another solution?
Thanks.
Edit:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main_activity, menu);
searchItem = menu.findItem(R.id.btn_earch);
initSearchView();
setSearchViewListener();
return super.onCreateOptionsMenu(menu);
}
protected void initSearchView() {
final String CURSOR_RESOURCE_ID = "mCursorDrawableRes";
final int THRESHOLD = 1;
mSearchView = (SearchView) searchItem.getActionView();
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setMeasureWithLargestChildEnabled(true);
autoCompleteTextView = (AutoCompleteTextView) mSearchView.findViewById(R.id.search_src_text);
autoCompleteTextView.setThreshold(THRESHOLD);
}
protected void setSearchViewListener() {
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (s!= null )
{
if (s.isEmpty()){
loadRecentList();
}
else{
search(s);
}
}
return true;
}
});
btn_search item:
<item
android:id="#+id/btn_search"
android:icon="#drawable/ic_search_small"
android:title="#string/tooltip_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"
/>

I solve it with something like this
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Log.i("MyApp", searchView.getQuery().toString());
consultarListaParadas(searchView.getQuery().toString());
getActivity().runOnUiThread(new Runnable() {
public void run() {
adaptadorListaParadasBus.setListaParadas(listaParadas);
adaptadorListaParadasBus.notifyDataSetChanged();
}
});
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText.equals("")){
this.onQueryTextSubmit("");
}
return true;
}
});
The only problem is that it throws without you press the search button.

#Gali,
Please take a look at my code:
1) I created ActionBar Activity like that:
public class CarsActivity extends ActionBarActivity implements ExpandableListView.OnGroupClickListener
{
//my class fields:
private MenuItem _menu_item;
private SearchView _searchView;
// .......
//here is my OnCreateOptionMenu method:
#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_cars_activity, menu);
_menu_item = menu.findItem(R.id.action_search);
_searchView = (SearchView) MenuItemCompat.getActionView(_menu_item);
_searchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View v)
{
//action when search is displayed on actinbar
}
#Override
public void onViewDetachedFromWindow(View v)
{
//action when search is collaped on actinbar
}
});
_searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s)
{
return true;
}
#Override
public boolean onQueryTextChange(String s)
{
//listener for entering text in searchView
//you can implement it your way
return false;
}
});
return true;
}
}
Hope it will help you.

The queryTextListener wont fire on an empty string event. A solution is to find the underlining EditText on the SearchView and attach a TextWatcher to that.
Recursive method to find a view of EditText
private EditText getEditText(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
View editText = getEditText(context, child);
if (editText instanceof EditText) {
return (EditText) editText;
}
}
} else if (v instanceof EditText) {
Log.d(LogUtil.RANDOM_TAG, "found edit text");
return (EditText) v;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
then when you have your SearchView
EditText et = getEditText(getActivity(), searchView);
if (et != null) {
et.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(TextUtils.isEmpty(s)){
Log.d(LogUtil.RANDOM_TAG, "empty");
//do stuff
}
else{
Log.d(LogUtil.RANDOM_TAG, "not empty");
}
}
});
}

you can achieve this by create custom SearchView widget like this :
import android.content.Context;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
public class EmptySubmitSearchView extends SearchView {
SearchView.SearchAutoComplete mSearchSrcTextView;
OnQueryTextListener listener;
public EmptySubmitSearchView(#NonNull Context context) {
super(context);
}
public EmptySubmitSearchView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public EmptySubmitSearchView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public void setOnQueryTextListener(OnQueryTextListener listener) {
super.setOnQueryTextListener(listener);
this.listener = listener;
mSearchSrcTextView = this.findViewById(androidx.appcompat.R.id.search_src_text);
mSearchSrcTextView.setOnEditorActionListener((textView, i, keyEvent) -> {
if (listener != null) {
listener.onQueryTextSubmit(getQuery().toString());
}
return true;
});
}
}
reference from this link, i just migrated it to support AndroidX

Related

When I split the char how can use spannable or ClickableSpan to get values?

When I split the char how can use spannable or ClickableSpan to get values?
this is a code
StringBuilder sb = new StringBuilder();
String data = newFeedModel.getFeedTags();
String[] items = data.split("#");
for (String item : items)
{
if(item.trim().length() == 0){
sb.append("");
}else{
sb.append("#"+item+"\n");
}
}
holder.tags.setText(sb.toString());
I will split all "#" char, like facebook function.
#aaa#bbbccc#xcvsdfsefsefa#22
it will split like this
#aaa
#bbbccc
#xcvsdfsefsefa
#22
but how to know when I split the char then can got correct gata?
Update:
public void onBindViewHolder(ViewHolder holder, int position) {
if(!TextUtils.isEmpty(newFeedModel.getFeedTags())){
holder.tags.setVisibility(View.VISIBLE);
String data = newFeedModel.getFeedTags();
holder.bind(data);
}
}
in MyClickableSpan
class MyClickableSpan extends ClickableSpan {
String clicked;
Context context;
public MyClickableSpan(Context context, String string) {
super();
this.context = context;
clicked = string;
}
public void onClick(View tv) {
Toast.makeText(context.getApplicationContext(), ""+clicked, Toast.LENGTH_LONG).show();
}
#Override
public void updateDrawState(TextPaint ds) {
ds.setUnderlineText(false); // set to false to remove underline
}
}
how can send the data to live search when user click the tags.
this is my live code
public void fetchSearch(String key)
{
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<SearchModel>> call = apiInterface.getSearch(key);
call.enqueue(new Callback<List<SearchModel>>() {
#Override
public void onResponse(Call<List<SearchModel>> call, retrofit2.Response<List<SearchModel>> response) {
searchModelList = response.body();
adapter = new NewSearchAdapter(getActivity(), searchModelList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<SearchModel>> call, Throwable t) {
}
});
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.search, menu);
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
fetchSearch(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
fetchSearch(newText);
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case R.id.message:
Intent intent = new Intent(getContext(), NotificationMessageActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}

How to hightlight the typed text in searchview in android

Hi in the MainActivity I was Implemented a Different Fragments.Now toolbar contains a searchview functionality I was added in my Activity.
Now I search for text all the fragement are also searching for same text.But I want to clear the text which one i typed for last fragement.
MainActivity:
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setSearchtollbar();
public void setSearchtollbar()
{
searchtollbar = (Toolbar) findViewById(R.id.searchtoolbar);
if (searchtollbar != null) {
searchtollbar.inflateMenu(R.menu.menu_search);
search_menu=searchtollbar.getMenu();
searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,false);
else
searchtollbar.setVisibility(View.GONE);
}
});
item_search = search_menu.findItem(R.id.action_filter_search);
MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
circleReveal(R.id.searchtoolbar,1,true,false);
}
else
searchtollbar.setVisibility(View.GONE);
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true;
}
});
initSearchView();
} else
Log.d("toolbar", "setSearchtollbar: NULL");
}
public void initSearchView()
{
final SearchView searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
// Enable/Disable Submit button in the keyboard
searchView.setSubmitButtonEnabled(false);
// Change search close button image
ImageView closeButton = searchView.findViewById(R.id.search_close_btn);
closeButton.setImageResource(R.drawable.ic_close_black_24dp);
// closeButton.setImageResource(ContextCompat.getDrawable(getApplication(), R.drawable.ic_close_black_24dp));
// set hint and the text colors
EditText txtSearch = ((EditText) searchView.findViewById(R.id.search_src_text));
txtSearch.setHint("Search..");
txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));
// set the cursor
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor); //This sets the cursor resource ID to 0 or #null which will make it visible on white background
} catch (Exception e) {
e.printStackTrace();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
callSearch(query);
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
callSearch(newText);
return true;
}
public void callSearch(String query) {
Log.i("query", "" + query);
}
});
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
{
final View myView = findViewById(viewID);
int width=myView.getWidth();
if(posFromRight>0)
width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
if(containsOverflow)
width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);
int cx=width;
int cy=myView.getHeight()/2;
Animator anim;
if(isShow)
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
else
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);
anim.setDuration((long)220);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(!isShow)
{
super.onAnimationEnd(animation);
myView.setVisibility(View.INVISIBLE);
}
}
});
// make the view visible and start the animation
if(isShow)
myView.setVisibility(View.VISIBLE);
// start the animation
anim.start();
}
Fragment:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
return true;
case R.id.refresh:
fetchJSON();
return true;
}
return true;
}
Menu:
<item android:id="#+id/search"
android:orderInCategory="0"
android:title="search"
android:icon="#drawable/ic_search"
app:showAsAction="always"/>

Android Searchview on Firebase Data

I want to implement the Android Searchview function in a listview fragment populated with data from a Firebase Database.
Code to get the Firebase Data
mPOIAdapter = new FirebaseListAdapter<Poi>(
getActivity(),
Poi.class,
R.layout.item_layout_poi,
FirebaseDatabase.getInstance().getReference("poi").orderByChild("name")) {
#Override
protected void populateView(View v, Poi model, int position) {
TextView pointsText = (TextView) v.findViewById(R.id.poi_textview);
pointsText.setText(model.getName());
TextView pointDescr = (TextView) v.findViewById(R.id.poi_building);
pointDescr.setText(model.getDescription());
}
};
mPOIListView.setAdapter(mPOIAdapter);
Searchview code :
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.options_menu,menu);
MenuItem item = menu.findItem(R.id.search);
item.setVisible(true);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
}
I want to use code like this to filter the Listview items based on the input of the users
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
getListAdapter().getFilter().filter(s);
return true;
}
});
Because the FirebaseListAdapter doesn't have the same possibilities as the ListAdapter, i can't use the getListAdapter().getFilter().filter(s)
Is there an alternative way to use the search function in a Listview fragment populated with Firebase Data
You don't need in any array just create new method "firebaseUserSearch"
the copy your RecyclerView adapter and paste inside. use you databaseReference to filter it.
My FB structure is :
BLABLA:
Bars:
01:
BarName: "Best bar"
02:
BarName: "The Worst bar"
And code is here:
....
databaseReference = FirebaseDatabase.getInstance().getReference ("Bars");
.....
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String searchText) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String searchText) {
searchText = searchView.getQuery().toString();
firebaseUserSearch (searchText);
return true;
}
});
return true;
}
private void firebaseUserSearch (final String searchText) {
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter <Bar, ViewHolder>(
Bar.class,
R.layout.custom_row,
ViewHolder.class,
databaseReference.orderByChild("barName").startAt(searchText.toUpperCase()).endAt(searchText + "\uf8ff"))
{
#Override
protected void populateViewHolder(ViewHolder viewHolder, Bar model, final int position) {
....
FirebaseDatabase.getInstance().getReference("poi").orderByChild("name").equalTo("anyName")) {
try this orderByChild("name").equalTo("nameString")
it'll check if there is any matched name belongs to name child. if there is any it'll show that to list

Search in custom ListView

the problem in search is start only of first word
example : search in "Real Madrid" , if search of "Madrid" not give result , but if search of "Real" give me result because the word "real" is first word
So what is the solution to this problem? Thank you :)
public void setAdapterToListview() {
objAdapter = new LatestGridAdapter(getActivity(), R.layout.latest_lsv_item,
arrayOfLatestVideo,columnWidth);
lsv_latest.setAdapter(objAdapter);
}
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_search, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
final MenuItem searchMenuItem = menu.findItem(R.id.search);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus) {
searchMenuItem.collapseActionView();
searchView.setQuery("", false);
}
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
textlength=newText.length();
arrayOfLatestVideo.clear();
for(int i=0;i< allArrayVideoName.length;i++)
{
if(textlength <= allArrayVideoName[i].length())
{
if(newText.toString().equalsIgnoreCase((String) allArrayVideoName[i].substring(0, textlength)))
{
ItemLatest objItem = new ItemLatest();
objItem.setId(Integer.parseInt(allArrayVideoId[i]));
objItem.setCategoryId(Integer.parseInt(allArrayVideoCatId[i]));
objItem.setCategoryName(allArrayVideoCatName[i]);
objItem.setDescription(allArrayVideoDesc[i]);
objItem.setVideoId(allArrayVideo[i]);
objItem.setVideoName(allArrayVideoName[i]);
objItem.setVideoUrl(allArrayVideourl[i]);
objItem.setImageUrl(allArrayImageUrl[i]);
arrayOfLatestVideo.add(objItem);
}
}
}
setAdapterToListview();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
// Do something
return true;
}
});
}
Try this method for searching. If it returns anything other than -1 it means that it's found a match. I turn everything into lowercase so you don't have to worry about case sensitivity.
#Override
public boolean onQueryTextChange(String newText) {
textlength=newText.length();
arrayOfLatestVideo.clear();
for(int i=0;i< allArrayVideoName.length;i++)
{
if(textlength <= allArrayVideoName[i].length())
{
if(allArrayVideoName[i].toLowerCase().indexOf(newText.toLowerCase())!=-1)
{
ItemLatest objItem = new ItemLatest();
objItem.setId(Integer.parseInt(allArrayVideoId[i]));
objItem.setCategoryId(Integer.parseInt(allArrayVideoCatId[i]));
objItem.setCategoryName(allArrayVideoCatName[i]);
objItem.setDescription(allArrayVideoDesc[i]);
objItem.setVideoId(allArrayVideo[i]);
objItem.setVideoName(allArrayVideoName[i]);
objItem.setVideoUrl(allArrayVideourl[i]);
objItem.setImageUrl(allArrayImageUrl[i]);
arrayOfLatestVideo.add(objItem);
}
}
}
setAdapterToListview();
return false;
}

onQueryTextChange triggered after app resume

I am stumbed with animated searchview onQueryTextListener. When activity and fragment created first it works nice. Then I press home button, open other apps, do some work there to wipe the data of searchview activity and then return to the app. And when activity and fragment resume onQueryTextChange method is triggered by it's own. I tried this issue
Fragment replacement triggers onQueryTextChange on searchview
but it did not help, helps only when searchview SHOW_AS_ACTION_NEVER, but in this case I can not see searchview. How to prevent self-triggering of OnQueryTextListener?
Snippet from fragment
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
searchView = new SearchView(getSherlockActivity().getSupportActionBar()
.getThemedContext());
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
fpAdapter.getFilter().filter(newText);
} else {
loadData();
}
return false;
}
});
TextView searchText = (TextView) searchView
.findViewById(R.id.abs__search_src_text);
searchText.setTextColor(Color.WHITE);
searchText.setCursorVisible(false);
ImageView searchButton = (ImageView) searchView
.findViewById(R.id.abs__search_button);
searchButton.setImageResource(R.drawable.search_menu_button);
LinearLayout searchEditFrame = (LinearLayout) searchView
.findViewById(R.id.abs__search_edit_frame);
searchEditFrame.setBackgroundResource(android.R.color.transparent);
View searchPlate = searchView.findViewById(R.id.abs__search_plate);
searchPlate.setBackgroundColor(Color.argb(0, 0, 0, 0));
menu.add("Search")
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
final MenuItem searchMenuItem = menu.getItem(0);
final Animation in = AnimationUtils.loadAnimation(getSherlockActivity()
.getApplicationContext(), R.anim.search_in);
final Animation out = AnimationUtils.loadAnimation(
getSherlockActivity().getApplicationContext(),
R.anim.search_out);
searchView.setQueryHint(getResources().getText(
R.string.search_messages_hint));
searchView.setIconifiedByDefault(true);
searchView
.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view,
boolean queryTextFocused) {
if (!queryTextFocused) {
// searchView.startAnimation(out);
searchMenuItem.collapseActionView();
} else {
searchView.startAnimation(in);
}
}
});
super.onCreateOptionsMenu(menu, inflater);
}
Update: This appears only in HTC sensation XL with Android 4.0.3, on 4.2 I don't see this problem.
Found the only one solution - set listener in onResume:
#Override
public void onResume() {
super.onResume();
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
fpAdapter.getFilter().filter(newText);
} else {
loadData();
}
return false;
}
}); }
use this code
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(final String s) {
if(searchView.getWidth()>0)
{
// your code here
}
return false;
}
});
You can set to use the SearchView only when it's in focus. I had a similar problem where the search was performing in my fragment every time when users resumed it. I solve it with the following method:
-Add a boolean to see when SearchView is in focus:
//by default the SearchView isn't in focus so set it to false.
private boolean shouldSearch = false;
searchView.setOnQueryTextFocusChangeListener((view, hasFocus) -> {
if (hasFocus) {
shouldSearch = true;
} else {
shouldSearch = false;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (shouldSearch) {
//do your search here
}
return true;
}
});
This is a known issue. You can fix by checking to see if the search is "iconified" i.e only showing the magnifying glass icon or if it is expanded ( which means the user is interacting with the search view)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
//your code here
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
//this will catch firing event
if (searchView.isIconified) {
return true
}
//your code here
return true
}
})

Categories

Resources