Use android design support library

Support Library Features

In this document

See also

The Android Support Library package contains several libraries that can be included in your application. Each of these libraries supports a specific range of Android platform versions and set of features.

This guide explains the important features and version support provided by the Support Libraries to help you decide which of them you should include in your application. In general, we recommend including the v4 support and v7 appcompat libraries, because they support a wide range of Android versions and provide APIs for recommended user interface patterns.

In order to use any of the following libraries, you must download the library files to your Android SDK installation. Follow the directions for downloading the Support Libraries in Support Library Setup to complete this step. You must take additional steps to include a specific Support Library in your application. See the end of each library section below for important information on how to include the library in your application.

v4 Support Library

This library is designed to be used with Android 1.6 (API level 4) and higher. It includes the largest set of APIs compared to the other libraries, including support for application components, user interface features, accessibility, data handling, network connectivity, and programming utilities. Here are a few of the key classes included in the v4 library:

  • App Components
    • Fragment — Adds support for encapsulation of user interface and functionality with Fragments, enabling applications to provide layouts that adjust between small and large-screen devices.
    • NotificationCompat — Adds support for rich notification features.
    • LocalBroadcastManager — Allows applications to easily register for and receive intents within a single application without broadcasting them globally.
  • User Interface
    • ViewPager — Adds a ViewGroup that manages the layout for the child views, which the user can swipe between.
    • PagerTitleStrip — Adds a non-interactive title strip, that can be added as a child of ViewPager .
    • PagerTabStrip — Adds a navigation widget for switching between paged views, that can also be used with ViewPager .
    • DrawerLayout — Adds support for creating a Navigation Drawer that can be pulled in from the edge of a window.
    • SlidingPaneLayout — Adds widget for creating linked summary and detail views that appropriately adapt to various screen sizes.
  • Accessibility
    • ExploreByTouchHelper — Adds a helper class for implementing accessibility support for custom views.
    • AccessibilityEventCompat — Adds support for AccessibilityEvent . For more information about implementing accessibility, see Accessibility.
    • AccessibilityNodeInfoCompat — Adds support for AccessibilityNodeInfo .
    • AccessibilityNodeProviderCompat — Adds support for AccessibilityNodeProvider .
    • AccessibilityDelegateCompat — Adds support for View.AccessibilityDelegate .
  • Content
    • Loader — Adds support for asynchronous loading of data. The library also provides concrete implementations of this class, including CursorLoader and AsyncTaskLoader .
    • FileProvider — Adds support for sharing of private files between applications.

There are many other APIs included in this library. For complete, detailed information about the v4 Support Library APIs, see the android.support.v4 package in the API reference.

After you download the Android Support Libraries, this library is located in the /extras/android/support/v4/ directory. The library does not contain user interface resources. To include it in your application project, follow the instructions for Adding libraries without resources.

Caution: Using dynamic dependencies, especially for higher version numbers, can cause unexpected version updates and regression incompatibilities.

The Gradle build script dependency identifier for this library is as follows:

Multidex Support Library

This library provides support for building apps with multiple Dalvik Executable (DEX) files. Apps that reference more than 65536 methods are required to use multidex configurations. For more information about using multidex, see Building Apps with Over 65K Methods.

After you download the Android Support Libraries, this library is located in the /extras/android/support/multidex/ directory. The library does not contain user interface resources. To include it in your application project, follow the instructions for Adding libraries without resources.

The Gradle build script dependency identifier for this library is as follows:

v7 Support Libraries

There are several libraries designed to be used with Android 2.1 (API level 7) and higher. These libraries provide specific feature sets and can be included in your application independently from each other.

v7 appcompat library

This library adds support for the Action Bar user interface design pattern. This library includes support for material design user interface implementations.

Читайте также:  Android emulator small screen

Note: This library depends on the v4 Support Library. If you are using Ant or Eclipse, make sure you include the v4 Support Library as part of this library’s classpath.

Here are a few of the key classes included in the v7 appcompat library:

  • ActionBar — Provides an implementation of the action bar user interface pattern. For more information on using the Action Bar, see the Action Bar developer guide.
  • AppCompatActivity — Adds an application activity class that can be used as a base class for activities that use the Support Library action bar implementation.
  • AppCompatDialog — Adds a dialog class that can be used as a base class for AppCompat themed dialogs.
  • ShareActionProvider — Adds support for a standardized sharing action (such as email or posting to social applications) that can be included in an action bar.

After you download the Android Support Libraries, this library is located in the /extras/android/support/v7/appcompat/ directory. The library contains user interface resources. To include it in your application project, follow the instructions for Adding libraries with resources.

The Gradle build script dependency identifier for this library is as follows:

v7 cardview library

This library adds support for the CardView widget, which lets you show information inside cards that have a consistent look on any app. These cards are useful for material design implementations, and are used extensively in layouts for TV apps.

After you download the Android Support Libraries, this library is located in the /extras/android/support/v7/cardview/ directory. The library contains user interface resources. To include it in your application project, follow the instructions for Adding libraries with resources.

The Gradle build script dependency identifier for this library is as follows:

v7 gridlayout library

After you download the Android Support Libraries, this library adds support for the GridLayout class, which allows you to arrange user interface elements using a grid of rectangular cells. For detailed information about the v7 gridlayout library APIs, see the android.support.v7.widget package in the API reference.

This library is located in the /extras/android/support/v7/gridlayout/ directory . The library contains user interface resources. To include it in your application project, follow the instructions for Adding libraries with resources.

The Gradle build script dependency identifier for this library is as follows:

v7 mediarouter library

This library provides MediaRouter , MediaRouteProvider , and related media classes that support Google Cast.

In general, the APIs in the v7 mediarouter library provide a means of controlling the routing of media channels and streams from the current device to external screens, speakers, and other destination devices. The library includes APIs for publishing app-specific media route providers, for discovering and selecting destination devices, for checking media status, and more. For detailed information about the v7 mediarouter library APIs, see the android.support.v7.media package in the API reference.

The v7 mediarouter library is located in the /extras/android/support/v7/mediarouter/ directory after you download the Android Support Library. It’s provided as a library project with a dependency on the v7 appcompat library, so you’ll need to include both libraries in your build path when setting up your project. For more information on how to set up your project, follow the instructions in Adding libraries with resources. If you are developing in Eclipse/ADT, make sure to include both the android-support-v7-mediarouter.jar and android-support-v7-appcompat.jar files.

If you are using Android Studio, all you need to do is specify the Gradle build script dependency identifier com.android.support:support-v7-mediarouter: , where » » is the minimum revision at which the library is available. For example:

The v7 mediarouter library APIs introduced in Support Library r18 are subject to change in later revisions of the Support Library. At this time, we recommend using the library only in connection with Google Cast.

v7 palette library

The v7 palette support library includes the Palette class, which lets you extract prominent colors from an image. For example, a music app could use a Palette object to extract the major colors from an album cover, and use those colors to build a color-coordinated song title card.

After you download the Android Support Libraries, this library is located in the /extras/android/support/v7/palette/ directory. The library does not contain user interface resources. To include it in your application project, follow the instructions for Adding libraries without resources.

The Gradle build script dependency identifier for this library is as follows:

v7 recyclerview library

The recyclerview library adds the RecyclerView class. This class provides support for the RecyclerView widget, a view for efficiently displaying large data sets by providing a limited window of data items.

After you download the Android Support Libraries, this library is located in the /extras/android/support/v7/recyclerview/ directory. The library contains user interface resources. To include it in your application project, follow the instructions for Adding libraries with resources.

Читайте также:  Search in android apple

The Gradle build script dependency identifier for this library is as follows:

v8 Support Library

This library is designed to be used with Android 2.2 (API level 8) and higher. This library provides specific feature sets and can be included in your application independently from other libraries.

v8 renderscript library

This library is designed to be used with Android (API level 8) and higher. It adds support for the RenderScript computation framework. These APIs are included in the android.support.v8.renderscript package. You should be aware that the steps for including these APIs in your application is very different from other support library APIs. For more information about using these APIs in your application, see the RenderScript developer guide.

Note: Use of RenderScript with the support library is supported with Android Studio and Gradle-based builds, as well as the Eclipse plugin and Ant build tools. The renderscript library is located in the build-tools/$VERSION/renderscript/ folder.

The following example shows the Gradle build script properties for this library:

v13 Support Library

This library is designed to be used for Android 3.2 (API level 13) and higher. It adds support for the Fragment user interface pattern with the ( FragmentCompat ) class and additional fragment support classes. For more information about fragments, see the Fragments developer guide. For detailed information about the v13 Support Library APIs, see the android.support.v13 package in the API reference.

After you download the Android Support Libraries, this library is located in the /extras/android/support/v13/ directory. The library does not contain user interface resources. To include it in your application project, follow the instructions for Adding libraries without resources.

The Gradle build script dependency identifier for this library is as follows:

v17 Leanback Library

The android.support.v17.leanback package provides APIs to support building user interfaces on TV devices. It provides a number of important widgets for TV apps. Some of the notable classes include:

  • BrowseFragment — A fragment for creating a primary layout for browsing categories and rows of media items.
  • DetailsFragment — A wrapper fragment for Leanback details screens.
  • PlaybackOverlayFragment — A subclass of DetailsFragment for displaying playback controls and related content.
  • SearchFragment — A fragment to handle searches. The fragment receives the user’s search request and passes it to the application-provided SearchResultProvider . The SearchResultProvider returns the search results to the SearchFragment , which renders them into a RowsFragment .

After you download the Android Support Libraries, this library is located in the /extras/android/support/v17/leanback directory. For more information on how to set up your project, follow the instructions in Adding libraries with resources.

The Gradle build script dependency identifier for this library is as follows:

Annotations Support Library

The Annotation package provides APIs to support adding annotation metadata to your apps.

After you download the Android Support Libraries, this library is located in the /extras/android/support/annotations directory. For more information on how to set up your project, follow the instructions in Adding libraries with resources.

The Gradle build script dependency identifier for this library is as follows:

Design Support Library

The Design package provides APIs to support adding material design components and patterns to your apps.

The Design Support library adds support for various material design components and patterns for app developers to build upon, such as navigation drawers, floating action buttons (FAB), snackbars, and tabs.

After you download the Android Support Libraries, this library is located in the /extras/android/support/design directory. For more information on how to set up your project, follow the instructions in Adding libraries with resources.

The Gradle build script dependency identifier for this library is as follows:

Источник

Android Design Support Library — поддержка компонентов Material Design в приложениях с Android 2.1 до Android 5+ (с примерами)

Android 5.0 Lollipop — один из самых значимых релизов системы Android , в немалой степени благодаря введению концепции Material Design, нового языка дизайна, который преобразил Android. Подробные спецификации помогают начать использовать Material Design, но не решают проблемы разработчиков, связанные с обеспечением обратной совместимости приложений.

Новая библиотека поддержки Android Design Support Library делает доступным весь набор компонентов материального дизайна для всех версий, начиная с Android 2.1 и выше:

  • Navigation View (для Navigation Drawer) — панель навигации
  • Floating Labels (для EditText) — плавающий ярлык
  • Floating Action Button (FAB) плавающая кнопка
  • Snackbar — всплывающее уведомление с кнопкой
  • Tabs — вкладки
  • Motion and Scroll framework — управление жестами и прокруткой

Как подключить Android Design Support Library в проект Android Studio

Обновите Android Support Repository в SDK менеджере. Для подключения Android Design Support Library в ваш проект добавьте строку в секцию зависимостей файла build.gradle:

Так как библиотека материального дизайна зависит от Support v4 и AppCompat Support Libraries, те будут включаться автоматически при добавлении библиотеки com.android.support:design:22.2.0 .

Все новые виджеты, перечисленные в этой статье, должны быть доступны в редакторе макетов Android Studio (на вкладке CustomView), для некоторых компонентов доступен предварительный просмотр.

Читайте также:  Как очистить андроид от рут прав

Navigation drawer является важным элементом навигации вашего приложения, он ориентирует и координирует пользователя, что особенно важно для пользователей-новичков. NavigationView делает это проще, обеспечивая каркас для панели навигации, а также возможность создавать новые элементы навигации через ресурсы меню.

Используйте NavigationView как DrawerLayout представление в макете, например:

Обратите внимание на два атрибута NavigationView:

  • app:headerLayout — устанавливает (опционально) макет, используемый для заголовка
  • app:menu подключает ресурсы меню для элементов навигации (которые также могут обновляться во время выполнения)

NavigationView обеспечивает взаимодействие со строкой состояния (status bar), как на устройствах с версией API21+.

Пример простого меню для Navigation Drawer с отмечаемыми пунктами:

Отмеченный в панели навигации пункт меню остается выделенным, обеспечивая пользователя информацией, какой пункт выбран.

Вы также можете использовать подзаголовки в меню на отдельные группы пунктов:

Вы будете получать обратные вызовы для выбранных элементов, установив слушатель OnNavigationItemSelectedListener , использующий метод setNavigationItemSelectedListener() . Это позволяет обрабатывать события выбора MenuItem , выполняя дополнительные действия, например изменение статуса отмеченных пунктов, загрузку нового контента, программное закрытие Navigation Drawer, или любые другие действия, которые могут потребоваться.

Floating Labels для EditText

Даже для скромного EditText нашлось улучшение в духе материального дизайна. EditText скрывает текст подсказки (hint) сразу после того, как пользователь начинает вводить текст. Вы можете теперь обернуть EditText в TextInputLayout , и текст подсказки отобразится в floating label выше EditText , демонстрируя пользователю подсказку во время ввода.

В дополнение к подсказке, можно отобразить сообщение об ошибке ниже EditText путем вызова метода setError() .

Подробнее процесс создания Floating Labels для EditText смотрите в видео:

Floating Action Button

Floating action button — это круглая кнопка, обозначающий основное действие в интерфейсе вашего приложения. FloatingActionButton из Android Design Support Library предоставляет единую последовательную реализацию FAB, используя цвета colorAccent из вашей темы по умолчанию.

В дополнение к обычному размеру плавающей кнопки действия, он также поддерживает мини-размер ( fabSize=»mini» ) для обеспечения визуальной целостности интерфейса и согласованности с другими элементами.

FloatingActionButton унаследован от ImageView , поэтому можно использовать атрибут макета android:src или, например, метод setImageDrawable() для установки иконки, отображаемой внутри FloatingActionButton .

Snackbar

Обратную связь о какое-либо действии в интерфейсе приложения можно обеспечить, используя snackbar. Снекбары отображаются в нижней части экрана и содержат текст и действие (кнопку). Они показываются в течении определенного времени, в зависимости от продолжительности подсветки экрана, затем скрываются автоматически. Кроме того, пользователи могут убрать его жестом до тайм-аута.

Для включения возможности взаимодействия со Snackbar путем смахивания его жестом или выполнения указанного действия. Это значительно более мощный, чем тосты, и в то же время очень удобный механизм обратной связи. Его API достаточно прост:

Обратите внимание на первый параметр метода make() — он определяет корневой View, по нижней границе которого будет отображаться всплывающее сообщение.

Tabs — вкладки

Переключение между различными режимами в вашем приложение через tabs (вкладки) — это не новая концепция материального дизайна. Но вкладки одинаково эффективны и в качестве top level navigation pattern, и для организации различных групп информации в рамках одного приложения (скажем, разные жанры музыки).

TabLayout из Android Design Support Library реализует как фиксированные вкладки, где ширина и высота делится поровну между всеми вкладками, а также вкладки с возможностью прокрутки, где вкладки не одинакового размера и с горизонтальной прокруткой. Вкладки могут быть добавлены программно:

Однако, если вы используете ViewPager для горизонтального свайпа между вкладками, вы можете создать вкладки прямо в вашем PagerAdapter методом getPageTitle() и затем соединить вместе, используя setupWithViewPager() . Это гарантирует, что при выборе заголовка ViewPager обновит содержимое выбранной вкладки.

CoordinatorLayout, жесты и прокрутка

Отличительные визуальные эффекты являются только одной частью материального дизайна. Другой важной частью интерфейса вашего приложения является движение. В то время как есть много элементов движения в Material Design, в том числе touch ripples и meaningful transitions, Android Design Support Library вводит новый компонент — CoordinatorLayout. Это макет, который обеспечивает дополнительный уровень контроля над событиями прикосновения между дочерними View, доступными в новой библиотеке поддержки com.android.support:design:22.2.0.

CoordinatorLayout и floating action buttons

Прекрасным примером взаимодействия CoordinatorLayout и floating action buttons является добавление FloatingActionButton дочерним элементом в CoordinatorLayout и передача CoordinatorLayout в метод Snackbar.make(). В итоге snackbar отображается не поверх плавающей кнопки FloatingActionButton, перекрывая ее, а использует дополнительные обратные вызовы (callbacks), предоставляемые CoordinatorLayout, чтобы автоматически сдвигать FAB вверх и возвращать к своей позиции. Анимация движения кнопки поддерживается на устройствах с Android 3.0 и выше — никакого дополнительного кода при этом не требуется.

CoordinatorLayout и Toolbar

Другой основной вариант использования для CoordinatorLayout касается панели приложения (ранее action bar) и методов скроллинга. Возможно, вы уже используете в Toolbar в ваших макетах. Android Design Support Library поднимает это на новый уровень: использование AppBarLayout позволяет компоненту Toolbar и другим View (например, вкладкам, созданным через TabLayout ) реагировать на события прокрутки в родственном View, отмеченном как ScrollingViewBehavior . Пример макета:

Источник

Оцените статью