Android Search View based on Material design guidelines.

Overview

MaterialSearchView

Android SearchView based on Material Design guidelines. The MaterialSearchView will overlay a Toolbar or ActionBar as well as display a ListView for the user to show suggested or recent searches.

Stable: Download Beta: Download

Build Status APK size

Android Arsenal License

Buy Me a Coffee at ko-fi.com

Download

To add the MaterialSearchView library to your Android Studio project, simply add the following gradle dependency:

implementation 'br.com.mauker.materialsearchview:materialsearchview:1.3.0-rc02'

This library is supported with a min SDK of 14.

Important note: If you're still using version 1.0.3, it's recommended to upgrade to the latest version as soon as possible. For more information, please see this issue.

New version note: MSV 2.0 is now on beta stage, if you wish to test it, get it by using:

implementation 'br.com.mauker.materialsearchview:materialsearchview:2.0.0-beta02'

Version 2.0 doesn't require the Content Provider setup and had some API changes which will be added to the documentation later on. For more details please take a look at the V_2.0 branch.

Important note on V 2.0: Since I'm using Coroutine Actors, which is marked as obsolete, you'll get a lint warning on each class that uses MSV, to get rid of those add this to your app build.gradle file:

kotlinOptions.freeCompilerArgs += [
        "-Xuse-experimental=kotlinx.coroutines.ExperimentalCoroutinesApi",
        "-Xuse-experimental=kotlinx.coroutines.ObsoleteCoroutinesApi"
]

Once the Actors methods are updated, I'll update the lib as well.

Setup

Before you can use this lib, you have to implement a class named MsvAuthority inside the br.com.mauker package on your app module, and it should have a public static String variable called CONTENT_AUTHORITY. Give it the value you want and don't forget to add the same name on your manifest file. The lib will use this file to set the Content Provider authority.

Example:

MsvAuthority.java

package br.com.mauker;

public class MsvAuthority {
    public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}

Or if you're using Kotlin:

MsvAuthority.kt

package br.com.mauker

object MsvAuthority {
    const val CONTENT_AUTHORITY: String = "br.com.mauker.materialsearchview.searchhistorydatabase"
}

AndroidManifest.xml

xml version="1.0" encoding="utf-8"?>
<manifest ...>

    <application ... >
        <provider
        android:name="br.com.mauker.materialsearchview.db.HistoryProvider"
        android:authorities="br.com.mauker.materialsearchview.searchhistorydatabase"
        android:exported="false"
        android:protectionLevel="signature"
        android:syncable="true"/>
    application>

manifest>

Proguard note: Some of you might experience some problems with Proguard deleting the authority class, to solve those problems, add the following lines on your proguard file:

-keep class br.com.mauker.MsvAuthority
-keepclassmembers class br.com.mauker.** { *; }

Usage

To open the search view on your app, add the following code to the end of your layout:

<br.com.mauker.materialsearchview.MaterialSearchView
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Then, inside your Activity get the reference:

// Activity:
val searchView: MaterialSearchView = findViewById(R.id.search_view)
  • To open the search view, simply call the searchView.openSearch() method.

  • To close the search view, call the searchView.closeSearch() method.

  • You can check if the view is open by using the searchView.isOpen() method.

  • As from Version 1.2.1 it's also possible to get the query anytime by using the searchView.getCurrentQuery() method.

  • To close the search view using the back button, put the following code on your Activity:

override fun onBackPressed() {
    if (searchView.isOpen) {
        // Close the search on the back button press.
        searchView.closeSearch()
    } else {
        super.onBackPressed()
    }
}

For more examples on how to use this lib, check the sample app code here.

Search history and suggestions

You can provide search suggestions by using the following methods:

  • addSuggestions(suggestions: Array)
  • addSuggestions(suggestions: List)

It's also possible to add a single suggestion using the following method:

  • addSuggestion(suggestion: String?)

To remove all the search suggestions use:

  • clearSuggestions()

And to remove a single suggestion, use the following method:

  • removeSuggestion(suggestion: String?)

The search history is automatically handled by the view, and it can be cleared by using:

  • clearHistory()

You can also remove both by using the method below:

  • clearAll()

Modifying the suggestion list behavior

The suggestion list is based on a ListView, and as such you can define the behavior of the item click by using the MaterialSearchView#setOnItemClickListener() method.

If you want to submit the query from the selected suggestion, you can use the snippet below:

searchView.setOnItemClickListener { _, _, position, _ -> 
    // Do something when the suggestion list is clicked.
    val suggestion = searchView.getSuggestionAtPosition(position)
    searchView.setQuery(suggestion, false)
}

If you just want to set the text on the search view text field when the user selects the suggestion, change the second argument from the searchView#setQuery() from true to false.

Styling the View

You can change how your MaterialSearchView looks like. To achieve that effect, try to add the following lines to your styles.xml:

<style name="MaterialSearchViewStyle">
        <style name="MaterialSearchViewStyle">
            <item name="searchBackground">@color/white_ishitem>
            <item name="searchVoiceIcon">@drawable/ic_action_voice_searchitem>
            <item name="searchCloseIcon">@drawable/ic_action_navigation_closeitem>
            <item name="searchBackIcon">@drawable/ic_action_navigation_arrow_backitem>
            <item name="searchSuggestionBackground">@color/search_layover_bgitem>
            <item name="historyIcon">@drawable/ic_history_whiteitem>
            <item name="suggestionIcon">@drawable/ic_action_search_whiteitem>
            <item name="listTextColor">@color/white_ishitem>
            <item name="searchBarHeight">?attr/actionBarSizeitem>
            <item name="voiceHintPrompt">@string/hint_promptitem>
            <item name="android:textColor">@color/blackitem>
            <item name="android:textColorHint">@color/gray_50item>
            <item name="android:hint">@string/search_hintitem>
            <item name="android:inputType">textCapWordsitem>
        style>
style>

Alternatively, you can also style the Search View programmatically by calling the methods:

  • setBackgroundColor(int color);
  • setTintAlpha(int alpha);
  • setSearchBarColor(int color);
  • setSearchBarHeight(int height);
  • setTextColor(int color);
  • setHintTextColor(int color);
  • setHint(String hint);
  • setVoiceHintPrompt(String voiceHint);
  • setVoiceIcon(DrawableRes int resourceId);
  • setClearIcon(DrawableRes int resourceId);
  • setBackIcon(DrawableRes int resourceId);
  • setSuggestionBackground(DrawableRes int resourceId);
  • setHistoryIcon(@DrawableRes int resourceId);
  • setSuggestionIcon(@DrawableRes int resourceId);
  • setListTextColor(int color);

And add this line on your br.com.mauker.materialsearchview.MaterialSearchView tag:

style="@style/MaterialSearchViewStyle"

So it'll look like:

<br.com.mauker.materialsearchview.MaterialSearchView
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    style="@style/MaterialSearchViewStyle"/>

Interfaces

Currently there are two interfaces that you can use to instantiate listeners for:

  • OnQueryTextListener: Use this interface to handle QueryTextChange or QueryTextSubmit events inside the MaterialSearchView.
  • SearchViewListener: You can use this interface to listen and handle the open or close events of the MaterialSearchView.

Languages

The MaterialSearchView supports the following languages:

  • English (en_US);
  • Brazillian Portuguese (pt_BR);
  • Italian (Thanks to Francesco Donzello);
  • French (Thanks to Robin);
  • Bosnian, Croatian and Serbian (Thanks to Luke);
  • Spanish (Thanks to Gloix).

Sample GIF

More Info

For more use cases, and some examples, you can check the sample app.

Credits

This library was created by Maurício Pessoa with contributions from:

JCenter version was made possible with help from:

This project was inspired by the MaterialSearchView library by krishnakapil.

License

The MaterialSearchView library is available under the Apache 2.0 License.

Comments
  • Force closes the app when running KitKat.

    Force closes the app when running KitKat.

    Everythings works fine with devices running Lollipop and higher. When I test the app with an emulator running Kitkat, it force closes and the logcat says:

    android.view.InflateException: Binary XML file line #27: Error inflating class br.com.mauker.materialsearchview.MaterialSearchView

    How can I fix this issue? Is there any change I can avoid it?

    bug 
    opened by GabrielKuka 22
  • Support for transparent status bar?

    Support for transparent status bar?

    This is how the library looks when I open the search on the screen I need it:

    http://imgur.com/a/DK5qN

    I have a navigation drawer here which is why the status bar is transparent. The Toolbar handles it just fine, showing up below the status bar. However when I initiate the SearchView, it goes behind the status bar.

    Is there a fix/solution for this? Maybe something I've just missed on my side possibly?

    Thanks.

    enhancement 
    opened by MiralDesai 15
  • Abandon Content Provider

    Abandon Content Provider

    To allow the use of the Content Provider as the database access, I had to do some hackish code which I'm not very proud of. So, one option to keep the support for search history and search suggestions is to change the CursorAdapter for something else, and abandon the Content Provider once and for all.

    enhancement help wanted 
    opened by Mauker1 14
  • Remove CoordinatorLayout and use an Interface Instead?

    Remove CoordinatorLayout and use an Interface Instead?

    Is it okay to update the widget to not use CoordinatorLayout as its main container?

    This is to encourage developers to layout the whole screen container (on either Activity or Fragment) as a CoordinatorLayout instead of placing it inside a widget individually. This is to also facilitate proper arrangement of AppBarLayout and other widgets that need to anticipate Behavior extensions.

    If you're worrying about having a dedicated SnackBar reaction, we can implement it on a listener instead. We can also prepare a custom Behavior extension if needed.

    enhancement 
    opened by peterbetos 13
  • error in adding Suggestions to search view

    error in adding Suggestions to search view

    This is my code. List<String> newWords = new ArrayList<>(); newWords.add("one"); newWords.add("two"); searchView.addSuggestions(newWords);

    This is error that I am getting. java.lang.NullPointerException: Attempt to invoke virtual method 'void br.com.mauker.materialsearchview.MaterialSearchView.addSuggestions(java.util.List)' on a null object reference

    opened by ambitamber 9
  • Adding suggestions Takes time and hangs the app

    Adding suggestions Takes time and hangs the app

    Hey! I have been using your View For implementation but when i add suggestions in onResume() , it hangs the app for 3-4 seconds while going in onResume() lifecycle.

    enhancement 
    opened by SahajRana 9
  • How to disable voice button in Kotlin

    How to disable voice button in Kotlin

    I have set up my searchview, but I would like to take away the voice button. How can I do that? I couldn't find a method for that. I also tried setVoiceIcon(null) but Kotlin gives me an error of a non-null type-thing.

    question 
    opened by GabrielKuka 7
  • Using SearchView in layout  together with navigation view

    Using SearchView in layout together with navigation view

    Hello! I have the following problem. When I use your view in the layout with navigation view, then when open the search and I click on item recycler view, search is minimized and lost all of the search results. How should I place your element, so that when you click on the free space on your element search was not closed. I also have another problem. The items in the list suggestions not selected. My current layout, you can see the following link: http://pastebin.com/3RKEmwY5 Detail problem: http://prntscr.com/dffvu4

    enhancement question 
    opened by volkdown 7
  •  Unknown URL content

    Unknown URL content

    java.lang.IllegalArgumentException: Unknown URL content://br.com.mauker.materialsearchview.defaultsearchhistorydatabase/history at android.content.ContentResolver.insert(ContentResolver.java:1233) at br.com.mauker.materialsearchview.MaterialSearchView.saveQueryToDb(MaterialSearchView.java:857) at br.com.mauker.materialsearchview.MaterialSearchView.onSubmitQuery(MaterialSearchView.java:626) at br.com.mauker.materialsearchview.MaterialSearchView.access$400(MaterialSearchView.java:52) at br.com.mauker.materialsearchview.MaterialSearchView$6.onEditorAction(MaterialSearchView.java:362) at android.widget.TextView.onEditorAction(TextView.java:4490) at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:139) at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:304) at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5298) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:708)

    question 
    opened by lvtanxi 7
  • problem.. when i use the library  in  layout ??

    problem.. when i use the library in layout ??

    Rendering Problems The following classes could not be instantiated:

    - br.com.mauker.materialsearchview.MaterialSearchView (Open Class, Show Exception, Clear Cache)
     Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE  
    Exception Details java.lang.NullPointerException   
    at br.com.mauker.materialsearchview.MaterialSearchView.isVoiceAvailable(MaterialSearchView.java:899)   at 
    br.com.mauker.materialsearchview.MaterialSearchView.displayVoiceButton(MaterialSearchView.java:434)   at
    br.com.mauker.materialsearchview.MaterialSearchView.init(MaterialSearchView.java:260)   at
     br.com.mauker.materialsearchview.MaterialSearchView.<init>(MaterialSearchView.java:205)   at 
    br.com.mauker.materialsearchview.MaterialSearchView.<init>(MaterialSearchView.java:193)   at 
    java.lang.reflect.Constructor.newInstance(Constructor.java:423)   at 
    android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:806)   at 
    android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:64)   at 
    android.view.LayoutInflater.rInflate(LayoutInflater.java:782)   at 
    android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:809)   at 
    android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:64)   at 
    android.view.LayoutInflater.rInflate(LayoutInflater.java:782)   at 
    android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:809)   at 
    android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:64)   at 
    android.view.LayoutInflater.rInflate(LayoutInflater.java:782)   at 
    android.view.LayoutInflater.inflate(LayoutInflater.java:504)   at 
    android.view.LayoutInflater.inflate(LayoutInflater.java:385)
    
    opened by arceleno 6
  • Integrate proguard rules inside the library folder

    Integrate proguard rules inside the library folder

    Would you be able to apply the following: http://stackoverflow.com/a/30801516/1931228 This is to prevent apps from forgetting to integrate the proguard rules.

    I'll be using your version of the library since it's currently full-featured. (Kudos 👍 ) I'll stop updating my fork 😃

    enhancement 
    opened by peterbetos 6
  • Move lib to mavenCentral

    Move lib to mavenCentral

    JFrog, the company that maintains the JCenter artifact repository used by many Android projects, recently announced the deprecation and upcoming retirement of JCenter. According to the announcement, JCenter will allow downloads of existing artifacts until February 1, 2022.

    Since MSV is hosted on JCenter, we need to move it to another artifact repository, like mavenCentral.

    opened by Mauker1 1
  • Using material search as a dependency results in build errors

    Using material search as a dependency results in build errors

    I've run MaterialSearchView successfully (from a cloned repo) but can't seem to get it to run as a dependency. After following the steps in the README, the project seems alright in android studio (all styles have their corresponding icon/color in the left pane in the IDE). Build fails, however, with message:

    C:\MyAndoridProject\app\src\main\res\layout\activity_main.xml:17: AAPT: error: attribute voiceIconEnabled (aka com.my.package:voiceIconEnabled) not found.

    Why is it looking in the current package for the respective resources instead of the gradle cache? Upon going to resource declarations from android studio I'm correctly pointed to the cache. The build, on the other hand, is not. Why?

    opened by msebi 0
  • OnItemClickListener on suggestion list item's TextView

    OnItemClickListener on suggestion list item's TextView

    Is there any possibility to attach OnItemClickListener to suggestions list item's TextView? The problem that I have encountered is that OnItemClickListener handler is only triggered after clicking on suggestion list item's background. When I click on suggestion list item's TextView nothing happens.

    possible-bug 
    opened by timonsword 1
Owner
Maurício C. P. Pessoa
Maurício C. P. Pessoa
KT Search - a kotlin multi-platform library that provides client functionality for Elasticsearch and Opensearch

KT Search Client KT Search is a kotlin multi-platform library that provides client functionality for Elasticsearch and Opensearch. It builds on other

Jilles van Gurp 40 Jan 4, 2023
Android Search View based on Material design guidelines.

Android SearchView based on Material Design guidelines. The MaterialSearchView will overlay a Toolbar or ActionBar as well as display a ListView for the user to show suggested or recent searches.

Maurício C. P. Pessoa 1.1k Nov 11, 2022
Material Design text field that comes in a box, based on (OLD) Google Material Design guidelines.

TextFieldBoxes A new Material Design text field that comes in a box, based on Google Material Design guidelines. ???? 中文看这里 UPDATE NOTICE 1.4.5 Releas

Mark Wang 769 Jan 7, 2023
📱 Android Library to implement Rich, Beautiful, Stylish 😍 Material Navigation View for your project with Material Design Guidelines. Easy to use.

Material NavigationView for Android ?? ?? Android Library to implement Rich, Beautiful Material Navigation View for your project with Material Design

Shreyas Patil 198 Dec 17, 2022
Bottom Navigation widget component inspired by the Google Material Design Guidelines at https://www.google.com/design/spec/components/bottom-navigation.html

Material Bottom Navigation Library Lightweight Bottom Navigation library component inspired by the Google Material Design Guidelines at https://www.go

Alessandro Crugnola 1.4k Dec 18, 2022
An implementation of tap targets from the Material Design guidelines for feature discovery.

TapTargetView An implementation of tap targets from Google's Material Design guidelines on feature discovery. Min SDK: 14 JavaDoc Installation TapTar

Keepsafe 5.2k Jan 9, 2023
An implementation of tap targets from the Material Design guidelines for feature discovery.

TapTargetView An implementation of tap targets from Google's Material Design guidelines on feature discovery. Min SDK: 14 JavaDoc Installation TapTar

Keepsafe 5.2k Dec 30, 2022
Material Design Search View Layout, now implemented in Google Maps, Dialer, etc

THIS PROJECT IS DEPRECATED Component is not maintained anymore. Implementation of Lollipop+ Dialer and Google Maps. DEMO Add in View Add to your layou

Sahil Dave 1.1k Dec 22, 2022
Material progress circle around any FloatingActionButton. 100% Guidelines.

FABProgressCircle Android library to provide a material progress circle around your FloatingActionButton. This component is compatible with any existe

Jorge Castillo 1.2k Nov 28, 2022
Material progress circle around any FloatingActionButton. 100% Guidelines.

FABProgressCircle Android library to provide a material progress circle around your FloatingActionButton. This component is compatible with any existe

Jorge Castillo 1.2k Jan 7, 2023
Animate a strike over any image to indicate on/off states. As seen in the Material Guidelines.

StrikedImageView Animate a strike over any image to indicate on/off states. As seen in the Material Guidelines. Gradle allprojects { repositories

null 9 Sep 21, 2022
CuteToast is an Material Design Custom Toast for Android | Custom Material Design Toast

CuteToast is an Android Custom Toast library that could be used instead of Default Toast. It does everything as Toast but with some extra spice.

K M Rejowan Ahmmed 12 Dec 17, 2022
Material Design Search Bar for Android

Material SearchBar Android Material Design Search Bar for Android This beautiful and easy to use library will help to add Lollipop Material Design Sea

Mansour 2k Dec 28, 2022
Android app to search for covid vaccine slots, turn on background search & get notifications when slots are available

CowinNotifier Android app to search for covid vaccine slots, turn on background search & get notifications when slots are available Glipmse of the App

Ujjwal Kumar Maharana 3 Dec 29, 2022
Image-search - An Image search android app with offline support

image-search Image search app built using bing image search API via paging 3. Fe

Suraj Vaishnav 3 Feb 17, 2022
A simple Cat Search app, performed the search by cat breed name, using MVVM clean Architecture.

CatSearchApp A simple Cat Search app, performed the search by cat breed name, using MVVM clean Architecture. The App is using the The Cat Api for sear

Mansingh Bhati 2 Oct 20, 2022
Anime-Info-Search-Jikan - Search Information about Anime

Anime-Info-Search-Jikan Search Information about Anime. Home Page Information Pa

null 3 Nov 13, 2022
A simple app to showcase Androids Material Design and some of the cool new cool stuff in Android Lollipop. RecyclerView, CardView, ActionBarDrawerToggle, DrawerLayout, Animations, Android Compat Design, Toolbar

#Android-LollipopShowcase This is a simple showcase to show off Android's all new Material Design and some other cool new stuff which is (new) in Andr

Mike Penz 1.8k Nov 10, 2022