Wowzer
Wowzer

Reputation: 1161

How to make a custom view respond to a search view?

after taking a look at the app by google called google keep, I was immediately curious on how exactly does the search of the app works.

Here is the image of the app: enter image description here

Whenever you search something, the card that doesn't match would disappear. How exactly do they achieve this because I think that the card are basically custom views and the layout is a custom layout. My problem is that I don't know how to implements a search for custom view.

Note: I have taken a look at some internet example online for search view and I can only find the implementation of searches for listview which is not precisely what I want.

Upvotes: 0

Views: 73

Answers (1)

Felipe Kelemen
Felipe Kelemen

Reputation: 176

I had a similar problem, so I made my Custom views properties (e.g. name, tag, id, etc...) into a single String spaced by a single space " ".

Something like this inside my CustomView class:

public String toString() {
    return (this.name + " " + this.tag + " " + this.coords + " " + this.id );
}

And then I filtered my Custom views through all current Custom views that were shown:

ArrayList<CustomView> filteredList = new ArrayList<>();
...

private void filter(String constraint) {
    for(CustomView view : AllViews) {
        if (!filteredList.contains(view))
            if (view.toString().toLowerCase().contains(constraint.toLowerCase())) {
                filteredList.add(view);
                break;
            }
        }
    }
    // Do something to add the filteredList to your adapter
    // and show the new list of CustomViews.
}

You can call filter(newText) method inside onQueryTextChange(String newText) from SearchView OnQueryTextListener().

This way, if whatever word you type in the SearchView is found anywhere in any CustomView, the correspondent CustomView will be visible, otherwise the view will "disappear".

Hope this helps.

Upvotes: 1

Related Questions