Using cards in android

RecyclerView и CardView. Новые виджеты в Android L

Как известно, в июне проходила очередная конференция Google I/O, в ходе которой было вкратце рассказано о двух новых виджетах. И поскольку на хабре об этих виджетах пока ничего не написано, я решил написать эту статью с простенькой демонстрацией.

Демо приложение доступно на гитхабе по ссылке.

Собственно, под катом можно прочесть пару слов о RecyclerView, CardView и о подключении соответствующих библиотек в Gradle. Также, можно посмотреть коротенькое видео, демонстрирующее стандартную анимацию операций со списком в RecyclerView.

RecyclerView

RecyclerView, по сути, является эволюцией одного из самых необходимых в Android-разработке виджетов — ListView. Собственно, предназначение у него ровно то же самое — отображать список элементов, но есть нюансы:

1. Обязательное использование паттерна ViewHolder. Если при использовании ListView можно было из-за отсутствия опыта использовать адаптер, создающий с нуля отдельное view для каждого элемента списка, что при большом размере списка могло обернуться меньшей отзывчивостью UI и использованием лишней памяти, то при работе с RecyclerView разработчика насильно приводят к имплементации этого паттерна. Посмотрим, как это выглядит в коде адаптера для RecyclerView:

2. LayoutManager. Для использования RecyclerView кроме адаптера вам необходимо передать ему с помощью метода setLayoutManager() объект класса, реализующего LayoutManager. Этот класс отвечает за работу с адаптером, именно он решает, переиспользовать View или создать новый, и соответственно, именно он дёргает методы onCreateViewHolder(), onBindViewHolder() и getItemCount() адаптера. Пока доступна только одна реализация этого класса — LinearLayoutManager, для создания кастомного LayoutManager, необходимо унаследоваться от RecyclerView.LayoutManager.

3. Анимация операций со списком. Если вы смотрели презентацию дизайна Material, то могли заметить, что одной из основных его особенностей является плавность UI, которая достигается с помощью повсеместного использования анимации. Наверняка, при особом желании можно добавить анимацию и в ListView, мне пока не приходилось этим заниматься, но в RecyclerView это делается парой строчек кода:
— для объекта RecyclerView указывается класс, имплементирующий анимацию:

— при добавлении или удалении элемента списка вызывается метод адаптера notifyItemInserted(int position) или notifyItemRemoved(int position) соответственно.
При желании можно написать собственную реализацию анимации, унаследовавшись от RecyclerView.ItemAnimator.

4. Сырость. Нужно помнить, что виджет пока сыроват, и, возможно, его ждут существенные изменения. Например сейчас в RecyclerView нет возможности задать header и footer списка, да и вообще в интернете о нём пока довольно мало информации.

Собственно и всё о RecyclerView, на гитхабе я выложил простенькое приложение, демонстрирующее, как можно использовать этот виджет. Запустив его, можно полюбоваться на анимацию добавления/удаления элемента (а можно посмотреть видео).

CardView

CardView — это виджет, имплементирующий такой элемент дизайна Material, как карточка. По сути это контейнер, у которого можно задавать радиус скругленности углов, цвет карточки и высоту по оси z.
Например, вот такой код верстки:

Читайте также:  Кэт гоес фишинг андроид

даст нам следующий результат:

Сборка проекта, использующего новые виджеты

compile ‘com.android.support:cardview-v7:+’
compile ‘com.android.support:recyclerview-v7:+’

Но эти библиотеки автоматически меняют minSdk нашей сборки на версию L, поэтому для нормальной работы в AndroidManifest следует прописать параметр:

Источник

Cardview with Recyclerview Android Example [beginners]

Cardview Android is a new widget for Android, which can be used to display a card sort of a layout in android. Cardview was introduced in Material Design in API level 21 (Android 5.0 i.e Lollipop).

Since, Cardview is part of material design.It’s such a view which has all material design properties, most importantly showing shadows according to the elevation.

The best part about this view is that it extends FrameLayout and it can be displayed on all the platforms of Android since it’s available through the Support v7 library.

The design of the cardview will be looks like,

In the above picture, every boxes made with cardview in android.

Before jumping into the coding part, Let’s see the Cardview XML attribute, that makes the cardview looks beautiful.

Cardview XML attribute

CardView_cardBackgroundColor : ColorStateList: The new ColorStateList to set for the card background

CardView_cardCornerRadius : float: The radius in pixels of the corners of the rectangle shape

CardView_cardElevation : float: The backward compatible elevation in pixels.

CardView_cardMaxElevation : float: The backward compatible maximum elevation in pixels.

CardView_cardPreventCornerOverlap : boolean: Whether CardView should add extra padding to content to avoid overlaps with the CardView corners.

CardView_cardUseCompatPadding : boolean: true> if CardView should add padding for the shadows on platforms Lollipop and above.

CardView_contentPadding : Sets the padding between the Card’s edges and the children of CardView.

CardView_contentPaddingBottom : int: The bottom padding in pixels

CardView_contentPaddingLeft : int: The left padding in pixels

CardView_contentPaddingRight : int: The right padding in pixels

Done with explanation about the android cardview. Let get into the coding part.

Cardview android example with Recyclerview

In this post, I am going to create cardview with recyclerview in android to list the movies with the image and the movie title.

example application demo,

Step 1 — Adding dependencies

In this example, I am using recyclerview with cardview. But I am not going deeper into recyclerview. I am already have a post on recyclerview in android.

Источник

Интеграция карт в ваше Android-приложение

Есть много разных идей, для реализации которых могут понадобиться карты на мобильных устройствах.
Возможности таких устройств позволяют довольно оперативно получать информацию о местоположении, графические данные и графические преобразования для отображения объёма ландшафта.

В данном статье я расскажу как интегрировать возможность просмотра карт для мобильных устройств на основе Android, на примере Yandex Карт и Google Maps.
Функционал библиотек этих компаний позволяет:

  • Перемещать карту
  • Изменять масштаб
  • Изменять виды карт
  • Получать события от карты

Начнём с отечественного производителя.

Yandex

Библиотеку Yandex MapKit можно скачать с GitHub’а, там же есть версия и для iOS.
Но прежде чем начать использовать, нам надо получить API-key, для этого идём на почту и пишем письмо в support@mobmaps.yandex.ru, указав в заголовке «Map Kit запрос API-ключа». В ответ вам пришлют письмо с указанием дополнительных ссылок на документацию, на правила использования и собственно с самим ключом в теле письма (а могут и не прислать, кстати).

Читайте также:  Доступ ко всем функциям андроид

Пока ждём письмо, берём библиотеку и прикрепляем её к проекту.

После долгого ожидания с кружкой кофе, знакомимся с содержимым письма и информации по ссылкам, берём ключик и пишем в вашем layout’е приложения следующий код:

где заместо «you are key» вставляем полученный ключ. Всё, карта есть.

Далее код показывает, как перемещать карту на заданную координату и использовать зум:

Google

Для использования Google Maps надо совершить куда более изощрённые действия. Я расскажу, как получить debug-key для использования карт, но процесс получения release версии похоже несколько замороченней, но я release ещё не получал.

Для получения debug-key, надо найти ваше хранилище ключей, для отладки.
По-умолчанию, путь будет выглядеть примерно так:

Затем открываем командную строку, переходим в каталог, куда установлена Java:

где путь_до_хранилища_ключей — свой путь до debug.keystore (осторожно, возможны проблемы с пробелами в пути).

После чего в том же окне будет выведен md5-ключ после «Certificate fingerprint (MD5)».
Идём по ссылке и регистрируем код.
После чего Google сгенерирует с нужным кодом для layout и встроенным кодом, берём его и вставляем к себе в layout.
Далее нам, надо наш Activity представить в примерно следующем виде:

Замечу, что Activity наследован должен быть от MapActivity хранящийся в com.google.android.maps.MapActivity.
А в манифесте прописать между тегами вставить:

И не забыть, про разрешение доступа в интернет для приложения:

В остальном функционал GoogleMaps и YandexMapKit весьма схож:

Как можно видеть, процесс интеграции карт в приложения довольно простой, а спектр использования довольно широк.
Более подробно можно ознакомиться ниже.

Определение собственной позиции

Чтобы немного расширить пример, приложу кусок кода:

Но для использования этого кода, в манифесте следует указать следующее разрешение:

Источник

Hands-on with Material Components for Android: Cards

Part 6 of a series covering practical usage of Material Components for Android

This post will be covering the features and API of Card components. To find out how to handle initial setup of Material Components for Android (including the Gradle dependency and creating an app theme), please see my original post:

Setting up a Material Components theme for Android

Attribute by attribute

Cards are sheets of surface material that contain content and actions related to a single subject. This content may include text, images, links and more, and may vary in size. While there are many patterns and variations in terms of content layout, the only required element is the card container.

Basic usage 🏁

A MaterialCardView can be included in your layout like so:

Checking ☑️

A MaterialCardView can be checked to indicate selection. There is no default behavior for enabling/disabling checked state; this can be done in response to long press, for example.

Firstly, checkable behavior needs to be enabled:

We can then toggle checked state (the below example is in response to a long click):

The UI changes include an overlay color and a checked icon:

The checked icon can be changed using the checkedIcon attribute. The various color options will be discussed in the “Theming” section below.

Читайте также:  Сбер банк для андроид

For an advanced checking sample using RecyclerView selection, see the Material Components for Android catalog.

Dragging and swipe-to-dismiss ☝️

MaterialCardView s have built-in support for state changes specific to dragging. As with checking, no default behavior exists to implement the dragging itself. The recommended way of doing this is with ViewDragHelper and the Material Components for Android catalog includes a handy implementation class; DraggableCoordinatorLayout .

Note: It would be useful if DraggableCoordinatorLayout were included in the core Material Components for Android library to allow it to be used without having to copy the class. At the time of writing, the latest release of Material Components for Android is 1.2.0-alpha06 and this is not the case. You can star the feature request for this on the issue tracker.

Firstly, we need to change the parent container to a DraggableCoordinatorLayout :

We can then add a callback and toggle dragged state:

The UI changes include an overlay color and (animated) increased elevation:

For an advanced dragging sample using RecyclerView drag-and-drop, see the Material Components for Android catalog.

Theming 🎨

Cards can be themed in terms of the three Material Theming subsystems: color, typography and shape. When implementing a global card style, extend the Widget.MaterialComponents.CardView style and reference it in your app theme with the materialCardViewStyle attribute.

Color

The color of the card background can be customized with the cardBackgroundColor attribute. This defaults to colorSurface .

As mentioned above, the foreground color of a card is used to indicate both checked and dragged state. As such, this requires a ColorStateList , meaning a for checked/dragged states is required. It is usually transparent but uses color to indicate checking/dragging, defaulting to colorPrimary (checked)/ colorOnSurface (dragged), with different opacities per state.

The tint color of the checked icon can be customized with the checkedIconTint attribute. This defaults to colorPrimary .

The color of an optional card stroke can be customized with the strokeColor attribute. This is disabled by default.

Lastly, the color of the card touch ripple can be customized with the rippleColor attribute. It too accepts a ColorStateList and defaults to colorOnSurface (unchecked)/ colorPrimary (checked), with different opacities per state.

Typography

There is no primary text as part of card components. Text included in the contents of a card will be styled according to the class/component used as well as the fontFamily app theme attribute.

Shape

The shape of a card background can be customized with the shapeAppearance attribute. This defaults to shapeAppearanceMediumComponent .

The elevation of a card can be customized with the cardElevation attribute. This defaults to 1dp.

Interestingly, the corner size of a card’s current shape appearance can be interpolated between 0.0 and 1.0. This can be useful in animations and transitions. Use MaterialCardView#setProgress and MaterialCardView#getProgress for this.

While not strictly shape theming, it is worth mentioning that the width of an optional card stroke can be adjusted with the strokeWidth attribute. This defaults to 0dp (and will not be rendered if no strokeColor is set, regardless of width).

Источник

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