Material search bar android

Material Design. Динамический Toolbar на живом примере

Уверен, что те, кто следят за изменениями в мире Android, заметили, что Toolbar начинает играть в приложениях всё более значимую роль. Например в последней версии Gmail клиента в Toolbar вынесен почти весь функционал по работе с почтой, а в новом Google Chrome Toolbar отвечает за работу с текстом страниц.

В данной статье я постараюсь рассказать о создании динамического Toolbar, который позволит пользователю работать с контентом четырьмя различными способами в рамках одного Activity. Мы рассмотрим весь процесс разработки Toolbar-a начиная с xml файлов стилей и заканчивая анимацией иконок, а в конце статьи я оставлю ссылку на GitHub репозиторий с примером полностью рабочего приложения.

Начнём с постановки задачи

Мы будем разрабатывать Toolbar для приложения, которое позволит пользователю следить за изменениями цен на акции. На главном экране будет расположен список всех акций, за которыми следит пользователь, мы также должны реализовать базовый функционал: удаление, поиск и сортировку акций. Вот так я реализовал этот функционал с помощью динамического Toolbar-a:

Стандартный режим Режим поиска Режим удаления Режим сортировки

Создаём xml файлы конфигураций

Итак, в первую очередь нам нужно создать xml файл самого Toolbar-a. Я советую сделать это в отдельном файле, так как в будущем мы скорее всего захотим использовать один и тот же (или похожий) Toolbar во всех Activity нашего приложения.

Теперь мы можем добавить toolbar.xml в xml Activity следующим образом:
res/layout/activity_main.xml

Поскольку в нашем Toolbar будет располагаться виджет поиска, мы можем настроить его внешний в вид в файле styles.xml нашего приложения. В 21 версии Android SDK появилось гораздо больше возможностей для кастомизации виджета поиска (SearchView Widget), вы можете посмотреть полный список атрибутов по этой ссылке: AppCompat v21 — Material Design for Pre-Lollipop Devices! В этом же файле мы зададим цвет нашего Toolbar.

И наконец создадим файл со списком всех элементов нашего Toolbar-а. Тут у нас есть несколько вариантов:

  • В начале создать только те элементы, которые будут видны в стандартном режиме, а затем в коде добавлять или удалять элементы при переходе между режимами.
  • Сразу создать все существующие элементы в xml файле, а в коде просто управлять их видимостью.

Я выбрал второй вариант так как у нас не так много элементов внутри Toolbar и нам нет смысла экономить память храня в ней только видимые элементы.

Также существует два способа создания элементов Toolbar:

    Создавать элементы внутри меню (Menu), как экземпляры класса MenuItem. Этот способ использовался в предыдущих версиях Анрдроид (API Level

Источник

Material search bar android

Cute library to implement SearchView in a Material Design Approach. Works from Android API 14 (ICS) and above.

#Native version Maybe it would be useful to take a look into the new official approach http://www.materialdoc.com/search-filter/

Читайте также:  Webp конвертер для андроид

Add the dependencies to your gradle file:

Add MaterialSearchView to your layout file along with the Toolbar (Add this block at the bottom of your layout, in order to display it over the rest of the view):

Add the search item into the menu file:

Add define it in the onCreateOptionsMenu:

Set the listeners:

Allow/Disable it in the code:

Handle the response:

Define them in the resources as a string-array:

Add them to the object:

#Custom cursor Create the drawable:

And add it to the object:

It is a little bit tricky but can be achieved using this:

Close on backpressed:

Pull requests are more than welcome, help me and others improve this awesome library.

The code is based in the Krishnakapil original concept.

About

Cute library to implement SearchView in a Material Design Approach

Источник

Material search bar android

Xamarin-Material SearchBar Android

Material Design Search Bar for Android.

Package Latest Release
Xamarin-MaterialSearchBar

This version is based on the fantastic version created by: Mansur Nashaev

The original one:

This beautiful and easy to use library will help to add Lollipop Material Design SearchView in your project.

Read the Wiki for advanced examples and options.

But now, let’s go deep into some code!

First to add Xamarin-MaterialSearchBar into your project you need to download the package from NuGet.

Next edit your XML and add the custom control:

After that you can edit your activity and add the following piece of code:

About

Material Design Search Bar for Android, based on Mansur Nashaev’s version

Источник

Android Search View based on Material design guidelines

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.

Download

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

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.

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

Or if you’re using Kotlin:

MsvAuthority.kt

AndroidManifest.xml

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:

Usage

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

Then, inside your Activity get the reference:

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 :

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(String[] suggestions)
  • addSuggestions(ArrayList suggestions)

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

To remove all the search suggestions use:

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

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

You can also remove both by using the method below:

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:

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:

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:

So it’ll look like:

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).

Источник

Material search bar android

Material SearchBar Android

Material Design Search Bar for Android

This beautiful and easy to use library will help to add Lollipop Material Design SearchView in your project.

to include SearchBar to your project:

add this code to the the project level build.gradle file

add the dependency to the the app level build.gradle file

then add SearchBar to your activity:

MaterialSearchBar has the following xml attributes:

Attribute Description
mt_speechMode if set to true, microphone icon will be displayed instead of search icon
mt_maxSuggestionsCount specifies the max number of search queries stored
mt_navIconEnabled set navigation icon enabled
mt_roundedSearchBarEnabled use capsule shaped searchbar on v21+ and revert to default on lower
mt_dividerColor set the colors of the suggestion and menu dividers
mt_searchBarColor set the main color of the searchbar
mt_menuIconDrawable set drawable of the menu icon
mt_searchIconDrawable set drawable of the search icon when speech mode is false
mt_speechIconDrawable set drawable of the speech icon when speech mode is true
mt_backIconDrawable set drawable of the back arrow icon
mt_clearIconDrawable set drawable of the clear icon
mt_navIconTint set tint color of nav/back animated icon
mt_menuIconTint set tint color of the menu icon
mt_searchIconTint set tint color search/speech icon
mt_backIconTint set tint color of the back arrow icon
mt_clearIconTint set tint color of the clear icon
mt_navIconUseTint should the animated nav icon use tint color
mt_menuIconUseTint should the menu icon use the tint color
mt_searchIconUseTint should the search/speech icon use the tint color
mt_backIconUseTint should the back icon use the tint color
mt_clearIconUseTint should the clear icon use the tint color
mt_hint set the text of the hint when the searchbar is focused and search query is empty
mt_placeholder set the placeholder text when the MaterialSearchBar is not focused
mt_textColor set text color
mt_hintColor set hint color
mt_placeholderColor set placeholder color
mt_textCursorTint set text cursors tint
mt_highlightedTextColor set the text highlight tint color

public methods:

  • addTextChangeListener(TextWatcher textWatcher)
  • clearSuggestions()
  • closeSearch()
  • openSearch()
  • getLastSuggestions()
  • getMenu()
  • getText()
  • hideSuggestionList()
  • inflateMenu(int menuResource)
  • inflateMenu(int menuResource, int icon)
  • isSearchOpened()
  • isSpeechModeEnabled()
  • isSuggestionsVisible()
  • setArrowIcon(int arrowIconResId)
  • setArrowIconTint(int arrowIconTint)
  • setCardViewElevation(int elevation)
  • setClearIcon(int clearIconResId)
  • setClearIconTint(int clearIconTint)
  • setCustomSuggestionAdapter(SuggestionsAdapter suggestionAdapter)
  • setDividerColor(int dividerColor)
  • setHint(CharSequence hintText)
  • setIconRippleStyle(boolean borderlessRippleEnabled)
  • setLastSuggestions(List suggestions)
  • setMaxSuggestionCount(int maxSuggestionsCount)
  • setMenuDividerEnabled(boolean menuDividerEnabled)
  • setMenuIcon(int menuIconResId)
  • setMenuIconTint(int menuIconTint)
  • setNavButtonEnabled(boolean navButtonEnabled)
  • setNavIconTint(int navIconTint)
  • setOnSearchActionListener(OnSearchActionListener onSearchActionListener)
  • setPlaceHolder(CharSequence placeholder)
  • setPlaceHolderColor(int placeholderColor)
  • setRoundedSearchBarEnabled(boolean roundedSearchBarEnabled)
  • setSearchIcon(int searchIconResId)
  • setSearchIconTint(int searchIconTint)
  • setSpeechModeEnabled(boolean speechMode)
  • setSuggestionsClickListener(SuggestionsAdapter.OnItemViewClickListener listener)
  • setText(String text)
  • setTextColor(int textColor)
  • setTextHighlightColor(int highlightedTextColor)
  • setTextHintColor(int hintColor)
  • showSuggestions()
  • updateLastSuggestions(List suggestions)

Styling Material SearchBar

Custom Style — styles.xml Create a custom style and use one of the provided styles as the parent.

OR

Custom Colors — colors.xml Simply set/change these colors(or some) and you have your custom style.

To save search queries when the activity is destroyed, use the method searchBar.getLastSuggestions() and then, to restore them use searchBar.setLastSuggestions(List ); as shown in the example below

Here is a simple example of using MaterialSearchBar

Источник

Читайте также:  Android one device manager
Оцените статью