- SwipeRefreshLayout
- Пример на Kotlin
- Устаревший пример для Java
- Обновляем список
- Новый SwipeRefreshLayout из библиотеки Android support — «потяните чтобы обновить»
- SwipeRefreshLayout: не сферический и не в вакууме
- Implementing Pull to Refresh Guide
- Android SwipeRefreshLayout – Android Pull/Swipe Down to Refresh
- Android Tutorial
- Android SwipeRefreshLayout
- Android SwipeRefreshLayout Project Structure
- Android SwipeRefreshLayout Code
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() со цветами).
Обновляем список
По такому же принципу обновляем данные в списке.
При каждой попытке обновить список будет добавляться текущая дата и время.
Не забывайте, что обновление может занимать длительное время и использовать сеть для получения данных. Поэтому следует позаботиться о выполнении в другом потоке.
Источник
Новый 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 в виде кода, чтобы было жить легче:
Источник
SwipeRefreshLayout: не сферический и не в вакууме
Про новый SwipeRefreshLayout из библиотеки Android support на Хабре уже писали, да и Google любезно выдаёт множество ссылок на подобные примеры. Их всех объединяет одно — в SwipeRefreshLayout добавляется единственное TextView или ListView, и через минуту разработчик с умилением глядит на работающую анимацию. А если нам интерфейс чуть посложнее надо?
Итак, у нас есть Activity с двумя элементами: сверху — панель фильтра, снизу — некое View (лишние теги удалены):
Нам всего-то нужно заменить LinearLayout на SwipeRefreshLayout. Точнее, просто заменить не получится — SwipeRefreshLayout позволяет иметь только один вложенный элемент. Давайте просто обернём LinearLayout в SwipeRefreshLayout:
Запускаем — работает! Правда, как-то странно работает: индикатор обновления то не появляется, то пропадает.
Материмся, гуглим, изучаем опыт предыдущих поколений. Оказывается, в SwipeRefreshLayout что попало класть нельзя. ScrollView можно, GridView можно, ListView можно, а больше ничего и нельзя. ListView и GridView нам совсем не подходят, а вот ScrollView можно попробовать. Оборачиваем наш многострадальный LinearLayout в ScrollView:
Обращаем внимание — Lint тут же требует изменить android:layout_height с match_parent на wrap_content у вложенных в ScrollView элементов.
Запускаем, и… видим только панель фильтра. А где же нижний View? А нет его. Точнее, он есть, но мы его не видим. Раньше LinearLayout растягивал его на всё свободное пространство благодаря match_parent, но теперь-то мы внутри ScrollView! А ScrollView потому и ScrollView, что никого внутри себя растягивать не собирается, потому что его содержимое может выходить за пределы самого ScrollView.
Выход — либо наше нижнее MyView должно иметь явную высоту (через android:minHeight или onMeasure()), либо у ScrollView должен быть установлен атрибут android:fillViewport=«true», который и заставит его растянуть нижний View.
Источник
Implementing Pull to Refresh Guide
In Android, the common «pull to refresh» UX concept is not built in to a ListView/RecyclerView. However, many Android applications would like to make use of this concept for their feeds. This is useful for all sorts of feeds such as a Twitter timeline. This effect can be achieved using the SwipeRefreshLayout class
SwipeRefreshLayout is a ViewGroup that can hold only one scrollable view as a child. This can be either a ScrollView or an AdapterView such as a ListView or a RecyclerView .
Edit your app/build.gradle file to include a library:
Make sure your libraries is up to date by adding to your root gradle.file :
Just like the previous section, wrap the scrollable view, in this case a RecyclerView with a SwipeRefreshLayout in the XML layout:
Make sure to have helper methods in your RecyclerView adapter to clear items from the underlying dataset or add items to it.
Next, we need to configure the SwipeRefreshLayout during view initialization in the activity. The activity that instantiates SwipeRefreshLayout should add an OnRefreshListener to be notified whenever the swipe to refresh gesture is completed.
The SwipeRefreshLayout will notify the listener each and every time the gesture is completed again; the listener is responsible for correctly determining when to actually initiate a refresh of its content.
Next, we need to configure the SwipeRefreshLayout during view initialization in the activity:
Note that upon successful reload, we must also signal that the refresh has completed by calling setRefreshing(false) . Also note that you should clear out old items before appending the new ones during a refresh.
If you are using SwipeRefreshLayout with Android’s new Paging Library, the data sources used to provide data to the RecyclerView need to be invalidated. Review this guide for more information.
Note: ListView is an old UI component that is no longer used in modern Android applications. Only refer this guide if you intend to update some old code that still relies on ListView.
Set SwipeRefreshLayout at the Layout you want the SwipeRefresh functionality
activity_main.xml
activity_main.xml
You could use a ScrollView instead a ListView
In the activity who points to activity_main.xml, which is main_activity(in this example), this code should be enough
main_activity.java
Now just run your application!
You could check this example on GitHub.
If you aren’t able to get the swipe to refresh working, check the following tips:
Did you accidentally call setContentView twice? Ensure that inside your activity, you’ve only called setContentView once as the 2nd line of your onCreate method.
Did you invoke setRefreshing(false) after data finished loading? With the swipe to refresh control, you are responsible for notifying the system once the new data has been loaded into the list. You must make sure to invoke setRefreshing only after the data has come back and not before. This means if you are loading data from the network, calling this within the onSuccess method.
Did you clear out the old items before updating the list? Make sure that in order for the new items to be displayed that you clear the list of any old items if needed. In other words, if you are replacing items in the list with new versions, be sure to remove the old versions from the adapter first with adapter.clear();
Are you using CoordinatorLayout? If you are using a CoordinatorLayout to manage scrolling, be sure to move the app:layout_behavior=»@string/appbar_scrolling_view_behavior» property to the SwipeRefreshLayout rather than the child RecyclerView or ListView .
Источник
Android SwipeRefreshLayout – Android Pull/Swipe Down to Refresh
Android Tutorial
In this tutorial we’ll discuss and implement Android Swipe Down to Refresh or Android Pull to Refresh the screen. This Android Material Design UI pattern is very commonly seen in many applications like Gmail, Facebook, Twitter and implemented using Android SwipeRefreshLayout.
Android SwipeRefreshLayout
Android SwipeRefreshLayout is a ViewGroup that can hold only one scrollable child. It can be either a ScrollView, ListView or RecyclerView. The basic need for a SwipeRefreshLayout is to allow the users to refresh the screen manually. This is pretty common in the Facebook Newsfeed screen. Before this layout was available in the support library, we had to resort to creating and detecting custom swipe down gestures to refresh let’s say a ListView.
This class consists of one important listener that is OnRefreshListener . On swiping down this listener is triggered and the OnRefresh() method is called. We can override this method according to our needs.
In this tutorial we’ll develop an application that consists of a ListView that on swipe down, refreshes the screen and shuffles the list rows.
Android SwipeRefreshLayout Project Structure
Android SwipeRefreshLayout Code
The activity_main.xml is given below.
We add a ListView inside a SwipeRefreshLayout in the layout as shown above.
The MainActivity.java class is given below.
- In the above code we’ve created an ArrayList of strings and add it to the ArrayAdapter object that’s later set onto the ListView.
- We’ve added a shuffle method that shuffles the whole ArrayList every time the onRefresh() is called.
- We’ve used the Collections framework method to randomly shuffle the ArrayList by setting a random seed as the current time in milli seconds.
- setRefreshing(false) is an important line of code. It notifies the SwipeRefreshLayout instance that the refreshing is completed and it should stop the refreshing loader animation.
- The default refreshing animation color is set to black. We can change it using the method setColorSchemeResources()
The output of the application in action is given below.
This brings an end to this tutorial. You can download the Android SwipeRefreshLayout project from the link below and play around with different ways you can refresh the android screen on pull down.
Источник