Convert Figma logo to code with AI

Mauker1 logoMaterialSearchView

Android Search View based on Material design guidelines.

1,078
154
1,078
23

Top Related Projects

Cute library to implement SearchView in a Material Design Approach

A search view that implements a floating search bar also known as persistent search

Material Design Search Bar for Android

Quick Overview

MaterialSearchView is an Android library that provides a customizable search view component following Material Design principles. It offers a seamless integration with the app's toolbar and supports voice search functionality, making it easy for developers to implement a robust search feature in their Android applications.

Pros

  • Easy integration with Android's Toolbar and ActionBar
  • Supports voice search functionality out of the box
  • Customizable appearance and behavior to match app's design
  • Smooth animations for a polished user experience

Cons

  • Limited documentation and examples for advanced customization
  • May require additional setup for complex search scenarios
  • Not actively maintained (last update was in 2018)
  • Some reported issues with compatibility in newer Android versions

Code Examples

  1. Basic setup in Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MaterialSearchView searchView = findViewById(R.id.search_view);
    searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            // Handle search query submission
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            // Handle search query text change
            return false;
        }
    });
}
  1. Customizing search view appearance:
MaterialSearchView searchView = findViewById(R.id.search_view);
searchView.setHint("Search...");
searchView.setHintTextColor(Color.GRAY);
searchView.setTextColor(Color.BLACK);
searchView.setBackgroundColor(Color.WHITE);
  1. Handling voice search:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == RESULT_OK) {
        ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        if (matches != null && matches.size() > 0) {
            String searchWrd = matches.get(0);
            if (!TextUtils.isEmpty(searchWrd)) {
                searchView.setQuery(searchWrd, false);
            }
        }
        return;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

Getting Started

  1. Add the JitPack repository to your project's build.gradle:
allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}
  1. Add the dependency to your app's build.gradle:
dependencies {
    implementation 'com.github.Mauker1:MaterialSearchView:1.2.3'
}
  1. Add the MaterialSearchView to your layout XML:
<br.com.mauker.materialsearchview.MaterialSearchView
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  1. Initialize and use the MaterialSearchView in your Activity or Fragment as shown in the code examples above.

Competitor Comparisons

Cute library to implement SearchView in a Material Design Approach

Pros of MaterialSearchView

  • More actively maintained with recent updates and bug fixes
  • Supports voice search functionality out of the box
  • Includes additional customization options for search suggestions

Cons of MaterialSearchView

  • Slightly larger library size, which may impact app performance
  • Less flexible in terms of custom layouts and animations
  • Requires more setup code for basic implementation

Code Comparison

MaterialSearchView:

MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        // Handle search query
        return false;
    }
});

MaterialSearchView:

MaterialSearchView mSearchView = (MaterialSearchView) findViewById(R.id.search_view);
mSearchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
    @Override
    public void onSearchViewShown() {
        // Do something when search view is shown
    }
});

Both libraries provide similar functionality for implementing a material design search view in Android applications. MaterialSearchView offers more features and customization options, but may require more setup and have a slightly larger footprint. MaterialSearchView is simpler to implement but may be less flexible for complex use cases. The choice between the two depends on the specific requirements of your project and the level of customization needed.

A search view that implements a floating search bar also known as persistent search

Pros of FloatingSearchView

  • More customizable UI with additional features like suggestions list and search bar animations
  • Better support for recent searches and search history
  • More active development and maintenance, with recent updates and bug fixes

Cons of FloatingSearchView

  • Larger library size and potentially higher complexity
  • May require more setup and configuration to achieve desired functionality
  • Some users report issues with performance on older devices

Code Comparison

MaterialSearchView:

MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        // Handle search query submission
        return false;
    }
});

FloatingSearchView:

FloatingSearchView searchView = findViewById(R.id.floating_search_view);
searchView.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
    @Override
    public void onSearchTextChanged(String oldQuery, String newQuery) {
        // Handle search query changes
    }
});

Both libraries provide search functionality for Android applications, but FloatingSearchView offers more advanced features and customization options. MaterialSearchView is simpler and may be easier to implement for basic search requirements. The choice between the two depends on the specific needs of your project and the level of complexity you're willing to manage.

Material Design Search Bar for Android

Pros of MaterialSearchBar

  • More customization options for the search bar appearance
  • Includes built-in speech recognition functionality
  • Offers a last suggestions feature for quicker searches

Cons of MaterialSearchBar

  • Larger library size, potentially impacting app performance
  • Less seamless integration with ActionBar/Toolbar

Code Comparison

MaterialSearchBar:

MaterialSearchBar searchBar = findViewById(R.id.searchBar);
searchBar.setHint("Search");
searchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
    @Override
    public void onSearchStateChanged(boolean enabled) {
        // Handle search state change
    }
});

MaterialSearchView:

MaterialSearchView searchView = findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        // Handle query submission
        return false;
    }
});

Both libraries provide easy-to-use search functionality for Android applications, but they differ in their approach and feature set. MaterialSearchBar offers more customization options and additional features like speech recognition, while MaterialSearchView provides a simpler integration with the ActionBar/Toolbar. The choice between the two depends on the specific requirements of your project, such as the need for advanced features or a more lightweight implementation.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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<String?>)
  • addSuggestions(suggestions: List<String?>)

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_ish</item>
            <item name="searchVoiceIcon">@drawable/ic_action_voice_search</item>
            <item name="searchCloseIcon">@drawable/ic_action_navigation_close</item>
            <item name="searchBackIcon">@drawable/ic_action_navigation_arrow_back</item>
            <item name="searchSuggestionBackground">@color/search_layover_bg</item>
            <item name="historyIcon">@drawable/ic_history_white</item>
            <item name="suggestionIcon">@drawable/ic_action_search_white</item>
            <item name="listTextColor">@color/white_ish</item>
            <item name="searchBarHeight">?attr/actionBarSize</item>
            <item name="voiceHintPrompt">@string/hint_prompt</item>
            <item name="android:textColor">@color/black</item>
            <item name="android:textColorHint">@color/gray_50</item>
            <item name="android:hint">@string/search_hint</item>
            <item name="android:inputType">textCapWords</item>
        </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.