- SwipeRefreshLayout
- Пример на Kotlin
- Устаревший пример для Java
- Обновляем список
- Layout swiping in android
- Layout swiping in android
- Swipe Layout to Hide & Show in Android – Kotlin & Java
- Kotlin Code to Swipe Layout to Hide & Show in Android
- How to Use this Utility Class in Kotlin
- Java Code for Swiping Layout to Hide & Show in Android
- How to Use this Class in Java
- Paramters in the initialize method
- Cancel the Swipe Gesture Listener
- Новый SwipeRefreshLayout из библиотеки Android support — «потяните чтобы обновить»
SwipeRefreshLayout
В марте 2014 года был представлен новый компонент android.support.v4.widget.SwipeRefreshLayout, который входил в состав библиотеки Support Library v4. Сейчас это отдельная библиотека в составе AndroidX.
Компонент позволяет отказаться от сторонних библиотек и собственных велосипедов для реализации шаблона «Pull to Refresh», когда пользователь сдвигает экран, чтобы обновить данные. Подобное поведение можно увидеть в клиентах для Твиттера, чтобы получить новую порцию твитов, не дожидаясь, когда список сообщений обновится самостоятельно.
Пример на Kotlin
В марте 2020 года обзавелась стабильной версией.
В методах setColorSchemeColors() или setColorSchemeResources() следует указать используемые цвета.
Компонент достаточно интересный с занимательной анимацией. Вначале анимация представляла собой цветные полоски под заголовком программы. Позже анимацию заменили в стиле Material Design, теперь это маленький кружочек, внутри которого крутятся цветные линии (или чёрная линия, если не использовать метод setColorSchemeResources() со цветами).
Запустите пример и потяните экран сверх вниз, чтобы увидеть эффект обновления данных.
Устаревший пример для Java
Обернём компоненты родительским элементом SwipeRefreshLayout. На панели инструментов данного компонента нет, поэтому придётся писать код вручную.
В примере реализуется интерфейс OnRefreshListener с методом onRefresh(), в котором следует обновить поступающие данные. В нашем случае просто генерируются случайные числа.
При первом появлении библиотеки использовался метод setColorScheme(), который объявлен устаревшим. Вместо него появились два новых метода setColorSchemeColors() и setColorSchemeResources(). Принцип остался тот же, вам нужно указать четыре цвета по константам Color.XXX или из ресурсов. Вы можете не использовать вызов метода с цветными линиями, тогда будет выводиться только чёрная линия по умолчанию.
Компонент достаточно интересный с занимательной анимацией. Вначале анимация представляла собой цветные полоски под заголовком программы, как представлено на видео.
Позже анимацию заменили в стиле Material Design, теперь это маленький кружочек, внутри которого крутятся цветные линии (или чёрная линия, если не использовать метод setColorSchemeResources() со цветами).
Обновляем список
По такому же принципу обновляем данные в списке.
При каждой попытке обновить список будет добавляться текущая дата и время.
Не забывайте, что обновление может занимать длительное время и использовать сеть для получения данных. Поэтому следует позаботиться о выполнении в другом потоке.
Источник
Layout swiping in android
A layout that you can swipe/slide to show another layout.
Drag mode normal:
Drag mode same_level:
- Flexible, easy to use with RecyclerView, ListView or any view that requires view binding.
- Four drag edges (left, right, top, bottom).
- Two drag modes:
- Normal (the secondary view is underneath the main view).
- Same level (the secondary view sticks to the edge of the main view).
- Able to open one row at a time.
- Minimum api level 9.
app:mode can be normal or same_level
app:dragEdge can be left , right , top or bottom
Use with RecyclerView, ListView, GridView.
In your Adapter class:
Optional, to restore/save the open/close state when the device’s orientation is changed:
app:minDistRequestDisallowParent : The minimum distance (in px or dp) to the closest drag edge that the SwipeRevealLayout will disallow the parent to intercept touch event. It basically means the minimum distance to swipe until a RecyclerView (or something similar) cannot be scrolled.
setSwipeListener(SwipeListener swipeListener) : set the listener for the layout. You can use the full interface SwipeListener or a simplified listener class SimpleSwipeListener
open(boolean animation) , close(boolean animation) : open/close the layout. If animation is set to false, the listener will not be called.
isOpened() , isClosed() : check if the layout is fully opened or closed.
setMinFlingVelocity(int velocity) : set the minimum fling velocity (dp/sec) to cause the layout to open/close.
setDragEdge(int edge) : Change the edge where the layout can be dragged from.
setLockDrag(boolean lock) : If set to true, the user cannot drag/swipe the layout.
Источник
Layout swiping in android
Android Swipe Layout
This is the brother of AndroidViewHover.
One year ago, I started to make an app named EverMemo with my good friends. The designer gave me a design picture, the design like this:
I found it was pretty hard to achieve this effect, cause you had to be very familiar with the Android Touch System. It was beyond my ability that moment, and I also noticed that there was no such a concept library.
Time passed, finally. as you see right now.
Before I made this, I actually found some libraries (eg.SwipeListView) that helps developers to integrate swiping with your UI component.
But it only works in ListView , and it has too many issues that they never care. What a pity!
When I start to make this library, I set some goals:
- Can be easily integrated in anywhere, ListView, GridView, ViewGroup etc.
- Can receive onOpen , onClose , onUpdate callbacks.
- Can notifiy the hidden children how much they have shown.
- Can be nested each other.
- Can handle complicate situation, just like this.
Источник
Swipe Layout to Hide & Show in Android – Kotlin & Java
In this tutorial, we will discuss how we can swipe layout to hide and show with animation in Android using Kotlin and Java. Below I have shared a utility class that you can add in your project and just call it using 2 lines of code and that’s it. It supports all 4 types of swipes left, right, top & bottom and you can allow only those which are required. By using this utility class we are going to achieve the following type of UI behavior upon swiping with a finger.
Swipe Left
Swipe Right
Swipe Top
Swipe Bottom
Kotlin Code to Swipe Layout to Hide & Show in Android
If you are developing your project in Kotlin create a new class with the name SwipeLayoutToHideAndShow.kt and copy-paste the following code in your class.
For Java code, please scroll down.
How to Use this Utility Class in Kotlin
You can add the swipe functionality to any of your layouts in Kotlin by calling the initialize method of the above utility class by adding the following code. The details about the parameters are explained below.
Java Code for Swiping Layout to Hide & Show in Android
The following code is the same as above but it’s in Java. So if you are developing your App in Java then create a class in your project with name SwipeLayoutToHideAndShow.java and add the following code in that.
How to Use this Class in Java
You can add the swipe functionality to any of your layouts by calling the initialize method of the above SwipeLayoutToHideAndShow class. The details about the parameters are explained below.
Paramters in the initialize method
As you can see in your class code there is a function initialize(…) that we need to call to activate swipe gesture on our layout. The explanation of the parameters is that the first parameter is the root layout. You can any layout here on which you want to handle the swipe gesture. 2nd parameter is the moving layout, that layout will move with the swipe gesture. The last parameter takes the array of all possible swipe directions you want to allow in your scenario. In the following code, All 4 types are passed so the layout will be able to move in all directions. But you can pass only those swipe directions which you want to allow in your case. These swipe direction types are already defined in an Interface inside the above class.
Cancel the Swipe Gesture Listener
You can cancel the swipe gesture by just call the cancel() method, as shown in the following code.
This utility class uses GestureDetector and OnTouchListener for handling the gestures. But we don’t need to go to the inner implementation of the SwipeLayoutToHideAndShow class code as it seems not required for now.
If you have any question feel free to ask in the following comments section.
Источник
Новый SwipeRefreshLayout из библиотеки Android support — «потяните чтобы обновить»
Тихо и незаметно вместе с обновлением библиотеки Android support до версии 19.1 в нее прокрался новый компонент, который часто бывает нужным и полезным в быту. Сей совсем крохотный росчерк я посвящаю ему, SwipeRefreshLayout.
Он добавляет функционал, который один мой коллега называет «резинка от трусов», а остальные знают этот UI-паттерн под названием «потяни, чтобы обновить». Он бывает нужен, когда есть какой-то контент, который пользователь хочет часто обновлять, и может это сделать, просто потянув контент жестом вниз, а потом отпустив.
Очень похоже, что компонент был создан для GoogleNow, а потом перекочевал в support lib (очень похожа анимация).
Алгоритм простой.
- Компонент «оборачивается» вокруг View или Layout, для которого нужно сделать обновление и может содержать только одного потомка (похоже на ScrollView).
- Устанавливается OnRefreshListener с одним единственным методом onRefresh(). Как на него реагировать — решаем сами.
- Когда нужно показать, что идет обновление (и запустить анимацию), вызываем метод setRefreshing(boolean) и передаем ему true. Наиболее логичным кажется вызов метода внутри onRefresh().
- Когда обновление закончено, вызываем метод setRefreshing(boolean) и передаем ему false.
Давайте попробуем набросать пример использования.
Наш XML (если нужно, можно и динамически создать компонент и добавить в него потомка, компонент наследуется от ViewGroup).
Теперь наша Activity, а именно метод onCreate:
В данном случае я сделал нашу Activity реализующей интерфейс OnRefreshListener
Обратите внимание на метод setColorScheme, он как раз и раскрашивает в разные цвета прогресс во время обновления. В видео ниже видно, о чем я говорю. Первый цвет из 4-х — цвет прогресса во время оттягивания контента вниз перед обновлением. Остальные — сменяющиеся цвета прогресса.
А теперь сам onRefresh();
UPD:
Для желающих добавил саму APK
Ссылка на APK в виде кода, чтобы было жить легче:
Источник