Android support design widgets

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 и выше — никакого дополнительного кода при этом не требуется.

Читайте также:  4pda gps test android что это

CoordinatorLayout и Toolbar

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

Источник

Material Design with the Android Design Support Library

Material Design, a new design language that gives design guidelines for Android apps and apps on other platforms, was introduced with the release of Android 5.0 Lollipop.

With it came new UI components such as the ‘Floating Action Button’. Implementing these new components while ensuring backward compatibility was typically a tedious process. Third party libraries would usually be needed to streamline the process.

At this year’s Google IO conference, Google introduced the Android Design Support Library which brings a number of important material design components to developers. The components are backwards compatible, with support back to Android 2.1 and implementing them is easier than previously. The library includes a navigation drawer view, floating labels for editing text, a floating action button, snackbar, tabs and a motion and scroll framework to tie them together. In this tutorial we’ll create an app that showcases these components.

Getting Started

You can find the final project code on gitHub.

Before getting started on the components, we’ll set up the project and set some styles. Using Android Studio, create a new Android project. Name it ‘Design Demo’ and leave the other settings as default, ensure the Minimum SDK version is at API level 15.

Add the following dependencies to the build.gradle (Module:app) file.

The first statement adds the design support library and the second the CardView library, which we’ll use later. Sync the project with the updated Gradle files. This may involve downloading some of the support libraries.

Create a resource file in the res/values folder called colors.xml. Modify it as below:

Modify res/values/strings.xml as below. These are all the Strings we’ll need for the project:

Modify res/values/styles.xml as below:

In the code above, we customize the app’s Color Palette by setting the primary, primary-dark and accent colors as specified in the material design guide.

Other theme settings that can be customized are shown in the image below.

Notice we do not include the android: prefix before the item name (e.g. android:colorPrimaryDark ). This is for backward compatibility. The android: annotation requires the minimum API level set to 21. We use a theme with NoActionBar because we’ll be using a Toolbar as our Action Bar (or AppBar as it is now called).

To create the Toolbar, modify res/layout/activity_main:

Above, we remove the default padding on the RelativeLayout and add a Toolbar from the support library. If you are supporting devices from API level 21 and above, you would only need to use the default Toolbar component and not one from the support library.

In MainActivity.java modify the onCreate(Bundle) method:

Download the project resources from gitHub which contains drawable folders that you can paste into the res directory so that the above code doesn’t result in errors.

When prompted by Android Studio, ensure you import the Toolbar from the support library.

In the above code, we get a reference to the Toolbar and set it as the Action Bar. We then get a reference of the Action Bar and set its Home icon to the infamous hamburger menu icon.

Run the app and you should see the Toolbar set as the app’s AppBar.

The Navigation Drawer is a common component in Android apps. It is one of the ways to build a navigation hierarchy on Android, the others being Tabs and Spinners. Implementing one was never a quick process, but now with the Design Support Library, its implementation is much simpler.

To get started, modify activity_main.xml as shown.

In the above code, we add a NavigationView to the layout. A NavigationView is placed within a DrawerLayout . Two important attributes to note are app:headerLayout which controls the (optional) layout used for the header and app:menu which is the menu resource inflated for the navigation items (this can also be updated at runtime).

Create a file labelled drawer_header.xml in the res/layout folder and modify it as shown.

This creates a header for the drawer that will have a background color of the app’s set primary color (in our case blue), with a height of 150dp and some text.

Next create a file named drawer.xml in the res/menu folder and modify it as shown.

In the above, we create the drawer’s menu items. The first part shows a collection of checkable menu items. The checked item will appear highlighted in the navigation drawer, ensuring the user knows which navigation item is currently selected. In the second part, we use a subheader to separate the second group of items from the first.

In MainActivity.java add the following member variable.

Then add the following to the bottom of onCreate(Bundle) .

Modify onOptionsItemSelected(MenuItem) as shown:

This will bring the drawer onto the screen when the Home button (the one with the hamburger menu icon) is tapped. Run the app and you should see the following.

To capture click events on the menu items we need to set an OnNavigationItemSelectedListener on the NavigationView . Place the following at the bottom of onCreate(Bundle) .

The above code sets a listener on the navigation view so that when a drawer menu item is selected, the menu item is set to checked (this will only affect the menu items marked as checkable), The drawer is closed and a Toast is shown displaying the title of the selected menu item.

Читайте также:  Flash player android downloads

In a real app you would do something like navigate to another Fragment and not just show a Toast. If you open the drawer again, you can confirm that the selected menu item is now checked by its highlight (only for the items marked checkable).

Floating Action Button (FAB)

A floating action button is a round button denoting a primary action on your interface. The Design library’s FloatingActionButton gives a single consistent implementation, by default colored using the colorAccent from your theme.

In addition to the normal size (56dp) floating action button, it supports the mini size (40dp) when visual continuity with other elements is critical.

To add a FAB to the layout, modify res/layout/activity_main.xml as shown.

In the above, we add the FloatingActionButton at the bottom right corner of the layout. android:src sets the icon shown within the button. In code, you can set this with setImageDrawable() .

Run the app, and you should see the FAB.

We’ll set an onClickListener on the FAB in the next section.

Snackbar

Traditionally, if you wanted to present quick brief feedback to the user, you would use a Toast. Now there is another option – the Snackbar.

Snackbars are shown at the bottom of the screen and contain text with an optional single action. They automatically time out after the given time by animating off the screen. Users can also swipe them away before the timeout.

By including the ability to interact with the Snackbar through actions and swiping to dismiss, they are considerably more powerful than toasts, and the API is familiar.

In MainActivity.java add the following to the bottom of onCreate(Bundle) :

In the above, we set an onClickListener on the FAB so that when it is tapped, a Snackbar will be shown. We create an Action on the Snackbar and set an onClickListener that displays a Toast when tapped.

Note the use of a View as the first parameter to make() . Snackbar will attempt to find an appropriate parent of the Snackbar’s view to ensure that it is anchored to the bottom. Run the app to test this.

Notice that the Snackbar overlaps the FAB. We’ll fix this in the section on CoordinatorLayout .

TabLayout

Using Tabs to switch between different views is not a new concept on Android. The Design library’s TabLayout simplifies the process of adding tabs to your app. It implements both fixed tabs, where the view’s width is divided equally between all of the tabs, as well as scrollable tabs, where the tabs are not a uniform size and can scroll horizontally.

To add a TabLayout to the app, modify res/layout/activity_main.xml as shown.

In the above, we add a TabLayout as well as a ViewPager . The ViewPager will be used to enable horizontal paging between tabs.

In MainActivity.java add the following subclasses.

Then at the bottom of onCreate(Bundle) add the following.

In the above, we create a Fragment class that creates a simple fragment with a single TextView as its content. We then create a FragmentStatePagerAdapter that will be used as the ViewPager ’s adapter. The getCount() function of the DesignDemoPagerAdapter class returns the number of pages/tabs. getItem(int) returns the Fragment that will be placed on the view page and getPageTitle(int) returns the title that will appear on a particular tab. For this to work, we use setupWithViewPager() on the TabLayout . This ensures that tab selection events update the ViewPager and page changes update the selected tab.

Run the app and you should see the tabs. You can swipe to change tabs or just tap on a tab to switch to it.

CoordinatorLayout

The Design library introduces the CoordinatorLayout , a layout which provides an additional level of control over touch events between child views, something which many of the components in the Design library take advantage of.

An example of this is when you add a FloatingActionButton as a child of your CoordinatorLayout and then pass that CoordinatorLayout to your Snackbar.make() call.

Instead of the snackbar displaying over the floating action button, as seen previously, the FloatingActionButton takes advantage of additional callbacks provided by CoordinatorLayout to automatically move upward as the snackbar animates in and returns to its position when the snackbar animates out. This is supported on Android 3.0 and higher devices.

To use the CoordinatorLayout in our layout, modify res/layout/activity_main.xml as shown:

As seen above, the FAB needs to be a child of the CoordinatorLayout , so we replace the previous RelativeLayout with the CoordinatorLayout . Also note that we change the FAB’s position setting to android:layout_gravity=»bottom|right» .

Next in MainActivity.java when constructing the Snackbar, pass the CoordinatorLayout as the view parameter.

Run the app and now when you tap on the FAB, the Snackbar will slide into view, but this time it won’t overlap the FAB, the FAB will slide up with it and when the Snackbar is dismissed either by timing out or with a swipe, the FAB will fall back into place.

The other main use case for the CoordinatorLayout concerns the app bar and scrolling techniques. The design library provides the AppBarLayout which allows the Toolbar and other views (such as tabs provided by TabLayout ) to react to scroll events in a sibling view marked with a ScrollingViewBehavior .

Before looking at this, let’s first create something we can scroll through. We’ll use a RecyclerView to create a list of items we can scroll through.

Note: I spent about an hour trying to make the CoordinatorLayout work with a ListView , but the scrolling behaviour was just not working. A simple search led me to this post, this post and this post. If you check those links, it seems that the CoordinatorLayout doesn’t work well out-of-the-box with ListViews (and apparently GridViews and ScrollViews ). The last two links show a workaround to making it work with a ListView , but it doesn’t seem to be backwards compatible. I wanted to let you know incase you get stuck on the same issue. Support for ListViews will probably be added in a future update.

Читайте также:  Что можно остановить андроид

I’ll go through the creation of the RecyclerView without much explanation as this is out of the scope of this tutorial and you can easily find help online regarding RecyclerViews .

Place the following in your build.gradle (Module: app) file and sync the gradle files..

Create a file in res/layout named fragment_list_view.xml. Modify it as shown.

Create another layout file in res/layout and name it list_row.xml. Replace its contents with the content below.

Create a java file called DesignDemoRecyclerAdapter.java and paste the following.

Modify DesignDemoFragment.onCreateView() in MainActivity.java as shown:

This inflates the previously created layout file. Now the fragment’s view will contain a list of items. Run the app to confirm this.

With that completed, we can look at the scrolling behaviour provided by the CoordinatorLayout .

Modify activity_main.xml as shown.

In the above, we nest the Toolbar and TabLayout in an AppBarLayout . The AppBarLayout allows the Toolbar and other views (such as tabs provided by TabLayout ) to react to scroll events in a sibling view marked with a ScrollingViewBehavior . When the user scrolls through the RecyclerView , the AppBarLayout responds by using its children’s scroll flags to control how they enter (scroll on screen) and exit (scroll off screen).

  • scroll: This flag should be set for all views that want to scroll off the screen. For views that do not use this flag, they’ll remain pinned to the top of the screen
  • enterAlways: This flag ensures that any downward scroll will cause this view to become visible, enabling the ‘quick return’ pattern
  • enterAlwaysCollapsed: When your view has declared a minHeight and you use this flag, your View will only enter at its minimum height (i.e., ‘collapsed’), only re-expanding to its full height when the scrolling view has reached it’s top.
  • exitUntilCollapsed: This flag causes the view to scroll off until it is ‘collapsed’ (its minHeight ) before exiting

Note that all views using the scroll flag must be declared before views that do not use the flag. This ensures that all views exit from the top, leaving the fixed elements behind.

In our app we use the scroll and enterAlways flags on the Toolbar which will result in the Toolbar scrolling off screen when scrolling upwards and come back on screen on the downward scroll. Notice the use of app:layout_behavior=»@string/appbar_scrolling_view_behavior» on the ViewPager. The support library contains a special string resource @string/appbar_scrolling_view_behavior that maps to AppBarLayout.ScrollingViewBehavior , which is used to notify the AppBarLayout when scroll events occur on a particular view. The behavior must be established on the view that triggers the event.

Run the app to see the effect of scrolling on the AppBar.

CollapsingToolbarLayout

The CollapsingToolbarLayour provides another type of scrolling behaviour to the AppBar . To see it in action, we’ll first create another activity that has a Toolbar , but no TabLayout .

Create a Blank Activity (File -> New -> Activity -> Blank Activity) and name it SecondActivity .

Modify res/layout/activity_second.xml as shown.

In the above, we use the CollapsingToolbarLayout with the scroll and exitUntilCollapsed flags which will make its subviews scroll off screen. For the Toolbar however, we set app:layout_collapseMode=»pin» which will ensure that the Toolbar itself remains pinned to the top of the screen while the view collapses. Another effect we’ll get is that the title in the CollapsingToolbarLayout will appear larger when the layout is fully visible, then transition to its default size as it is collapsed. We’ll set this title in code. The rest of the layout contains a NestedScrollView with several Cards as its children.

In SecondActivity.java modify onCreate(Bundle) as shown.

Here we set up the Up caret on the Toolbar and then set a title for the CollapsingToolbarLayout .

For the Up caret to work, place the following in the manifest file as a child of the SecondActivity ’s activity tag.

In DesignDemoRecyclerAdapter.java modify `onBindViewHolder() as shown.

In the above, we set an onClick Listener to the TextView on each row of the RecyclerView . This is not the best way of setting a listener on the RecyclerView items, because if you run the app, the listener’s touch target will only cover the area with the row’s text and not the whole row. I do this here because all I want is a way to start the new activity and so I opted on a way to write the least amount of code.

Run the app and you will see the following scrolling behaviour.

Floating Labels for EditText

The last component of the Design Support Library that we’ll look at is the improved EditText . Normally when typing is started on an EditText , the placeholder hint that was on the field is hidden. Now you can wrap an EditText in a TextInputLayout causing the hint text to become a floating label above the EditText , ensuring that users never lose context in what they are entering.

To see this, place the following inside one of the CardViews in activity_second.xml. You can place it after the second TextView of the Card.

Run the app and when you start to type into the EditText, the hint text will float above the field.

In addition to showing hints, you can display an error message below the EditText by calling setError() .

Conclusion

That brings us to the end of this tutorial. The completed project for the tutorial can be downloaded here. For more on the Android Design Support Library, read the Android developers blog.

Источник

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