Pull to refresh android kotlin

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() со цветами).

Обновляем список

По такому же принципу обновляем данные в списке.

При каждой попытке обновить список будет добавляться текущая дата и время.

Не забывайте, что обновление может занимать длительное время и использовать сеть для получения данных. Поэтому следует позаботиться о выполнении в другом потоке.

Источник

Работающий Pull to refresh

Это рассказ о том, как получилась работающая реализация Pull to refresh под Android. Совсем не будет примеров кода. Немного картинок и в конце статьи ссылка на архив проекта.

Недавно встала необходимость встроить в текущее приложение Pull to refresh. Это сейчас модно, пользователи привыкли, и для твиттер-клиентов уже стало стандартом. Поиск готовых решений в сети вывел на единственный вариант — open-source проект Johan Nilsson android-pulltorefresh на Github.

В ListView вставляется Header, который прячется при необходимости. Решение работающее, но очень криво. Часто подвисает в каком-либо состоянии. Если в списке мало элементов и они не занимают все пространство, отведенное для ListView, то Header не скрывается, а надпись изменяется на Tap to refresh. Логичное ограничение данной реализации. Еще одна особенность была обнаружена при добавлении этого проекта в рабочее приложение. Так как Pull to refresh — это Header, то часто выполняется метод setSelection(1), чтобы спрятать Header. А так как мы используем сохранение и восстановление позиции, то конечно постоянный вызов setSelection нам все портит.

Поначалу решили доработать эту реализацию, исправить самые неприятные моменты. Даже встроили в один проект. Но сделать так, как хочется, не получилось, сказались ограничения от использования Header’а.

Читайте также:  Samsung a31 обновление до android 11

Возникла идея, как сделать по-другому и появилось свободное время. Раз проблема в Header’е, значит, его нужно убрать и поместить сам Pull to refresh View и ListView в один LinearLayout и двигать его. В идеале хотелось получить такой же Pull to refresh как в официальном Twitter-клиенте. Но там используется другая связка. Pull to refresh там плавный и хорошо везде работающий. Вообще много времени провели, наблюдая за работой официального Twitter-клиента.

Вариантов что и как двигать много. Можно двигать и Pull to refresh View, и ListView, и LinearLayout. Можно двигать, изменяя Padding, Margin или ScrollTo. После большого количества экспериментов на эмуляторе и на реальных устройствах, была найдена наиболее оптимальная связка. Первоначальный сдвиг делается изменением Padding на высоту Pull to refresh View, таким образом, мы его прячем с экрана. А дальше двигаем весь Layout изменением ScrollTo.

Получилось красиво и максимально плавно. Но возникла проблема, на тот момент кажущаяся непреодолимой. Почему-то при сдвиге Layout все начинало прыгать. Приходили координаты то ниже, то выше, и никак не получалось исправить. Чуть даже не вернулись к первоначальному плану — доработать Pull to refresh от Johan Nilsson.

Но потом как по волшебству на глаза попал другой проект. Альтернативный Pull To Refresh от guillep на том же Github. Он еще ужаснее работает, чем у Johan Nilsson, но используется совсем другой механизм, похожий на нашу идею. И самое главное там обходится проблема с прыгающим Layout’ом. Берется три последних координаты и вычисляется средняя. Таким образом, обеспечивается плавность.

Мы взяли понемногу из каждого проекта, все объединили, и получился хорошо работающий Pull to refresh, но оставалось незаконченным состояние загрузки. После отпускания Release to refresh превращается в Loading и в таком состоянии оно должно скролиться вместе со списком, поэтому оно должно быть частью ListView. Отдельный Pull to refresh View должен исчезнуть, а в ListView должно добавиться Pull to refresh View в состоянии Loading.

Так как наше View должно постоянно то появляться, то исчезать в ListView, использовать его как Header нельзя. Но и изменять текущие адаптеры тоже не хочется. Необходимо, чтобы при добавлении Pull to refresh в рабочий проект, было как можно меньше изменений. Решили использовать специальный Adapter внутри Pull to refresh как Декоратор. И этот адаптер контролирует наличие специального View в состоянии Loading.

Было много проблем, особенно при добавлении в рабочий проект, но все они успешно решились. В конце концов, получился класс, которым можно заменять обычный ListView и в котором реализован хорошо работающий Pull to refresh. Он прекрасно работает на всех API, начиная с версии 1.5.

Только на некоторых устройствах Samsung с переделанным ListView наблюдаются иногда проблемы. Но уже есть идеи как и что можно переделать.

Источник

Add Pull To Refresh to your Android app using Kotlin

UPDATE [November 16th, 2020]: From now on, you need to add the SwipeRefreshLayout library

Pull to Refresh is used in many popular apps, apps where content updates are frequent, like news, social media e.t.c.

In Android development this gesture it’s called ‘Swipe to Refresh‘.

Add Pull To Refresh to our app

Go to your app-level build.gradle file and add the following library:

Next, in our XML layout, we have to change the parent layout to LinearLayout and add the orientation to vertical (or use ConstraintLayout).

Then, we have to add the SwipeRefreshLayout, this adds the pull to refresh gesture, and inside that, we’ll add the RecyclerView, like this:

After our layout is ready, let’s go to our file with the RecyclerView. In this example, it’s the MainActivity.kt, and set the Color Scheme for our Pull To Refresh icon.

Also, we’re going to set the setOnRefreshListener. This listener called every time we pull down to refresh.

Читайте также:  Полный сброс андроид honor полностью

Inside in the setOnRefreshListener listener what we do is:

  • Clean our array from the previous data (line 24)
  • Call backend to download the data again. In our example, it just creates a list of numbers (line 25)
  • Pass the adapter to RecyclerView’s adapter (lines 26 – 27)
  • Stop Pull-To-Refresh animation (line 28)

If you have any questions, please feel free to leave a comment below

Источник

Pull to Refresh with RecyclerView in Android with Example

The SwipeRefreshLayout widget is used for implementing a swipe-to-refresh user interface design pattern. Where the user uses the vertical swipe gesture to refresh the content of the views. The vertical swipe is detected by the SwipeRefreshLayout widget and it displays a distinct progress bar and triggers the callback methods in the app. In order to use this behavior, we need to use the SwipeRefreshLayout widget as the parent of a ListView or GridView. These Material Design UI Patterns are seen in applications like Gmail, Youtube, Facebook, Instagram, etc. It allows the user to refresh the application manually. SwipeRefreshLayout class contains a listener called OnRefreshListener. The classes which want to use this listener should implement SwipeRefreshLayout.OnRefreshListener interface. On vertical swipe-down gesture, this listener is triggered and onRefresh() method is called and can be overridden according to the needs.

Example

In this example, we would store data into the ArrayList which is used for populating the RecyclerView. Whenever onRefresh() method is called the ArrayList data gets rearranged. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Adding dependencies

Источник

Swipe To Refresh RecyclerView Android Example | Pull To Refresh

Welcome to Swipe To Refresh RecyclerView Android Example.

This Pull/swipe To Refresh RecyclerView Android Example will answer your question like “how to refresh recyclerview in android”

Swipe or pull to refresh recyclerview feature provides easy way to handle data which are updating frequently.

In this example, we will use three different lists to implement refresh facility.

One list is of cars, second is of player names and third one is of country names. I have created video for more reference.

First of all, go through the below video to show the final outcome.

Step 1. Adding Gradle File Lines

Create a new project in the android studio.

For using RecyclerView and CardView, you need to add two lines into your build.gradle(Module:app) file.

Below are those two lines,

First one is for RecyclerView and second one is for CardView.

These lines will add some classes to our projects which we can use directly in our Java files.

Step 2. Single Drawable File

Now go to app->res->drawable directory and create a new file called cardview.xml

You need to add the below code lines in this cardview.xml file.

Above lines will create the background for cardview.

It will use the gradient effect of blue colors to make attractive background for cardview.

We will use this file inside the XML layout file which we will create in the next step.

Step 3. Specific XML layout file

Now navigate to app->res->layout directory and make a new XML file.

Give this file a name like rv_child.xml and add the below code in it

We are using tag in the above file.

All the elements which are inside the tag will have the background like the cards.

In this, we have inserted one text view.

Читайте также:  Huawei mobiles with android

In the background of this text view, we are using an XML file which we have created in drawable folder. (cardview.xml)

All the child rows of the recyclerview will have the view created by this rv_child.xml file.

Step 4. Model For DataSet

Now make a new JAVA class and give it a name like Model.java

Write down the below code lines in Model.java file.

There is one string variable called “name” in the above class.

For this string variable, I have created two methods.

One is getter ( getName() ) and another is setter ( setName(String name) ) .

These methods will help us to maintain the data among all the child rows of the recycler view.

We will use this class and it’s objects in the Adapter class.

Step 5. Making Adapter

Time to create adapter class. Create a new JAVA class with the name Adapter.java

Adapter.java should contain the following coding lines.

Inside the constructor of the adapter class, compiler will get the arraylist with the objects of the Model.java class.

Name of this arraylist is imageModelArrayList

Now focus on the method onCreateViewHolder().

Inside this onCreateViewHolder() method, compiler will first inflate the rv_child.xml file.

Now read the method onBindViewHolder() . Inside this onBindViewHolder() method, compiler will set the text inside the text view.

To set the text inside text view, compiler will use imageModelArrayList and the methods of Model.java class.

Step 6. Final Writings of Example

Now there should be two main files when you created a new project.

Those two main files are : activity_main.xml and MainActivity.java

Inside activity_main.xml file, you have to write the below source lines

Above main XML layout file is very simple.

We need to add only RecyclerView inside this main layout file.

But we need to implement SwipeToRefresh element as the parent of the RecyclerView.

Now go to your MainActivity.java file and write the following words in it

More Details on Main File

First of all, see the below

First line is the object of RecyclerView class. Second is the arraylist with the object of the Model.java class.

Third line is the object of the Adapter class. Fourth one is integer variable.

Fifth is the object of the SwipeRefreshLayout class.

Now read the below lines

You can see that there are three string arrays are there.

All three includes the names of vehicles,players and countries respectively.

We will use all these three lists to set in the recycler view.

You can see the below lines in the onCreate() method.

Above line is populating the data inside the imageModelArrayList using populateList() method.

Below are the code lines for populateList() method.

This method will get one integer value inside it’s parameter (int number). This integer value is defining which names recyclerview should display.

If it’s value is 0 then compiler will display vehicle names, for the value 1, it will display player names and for value 2 it will display country names in the recyclerview.

Now read the following source code snippet

When the user pull or swipe down the recyclerview, compiler will run the above lines.

Here, compiler will check the value of the integer variable currentList.

If it’s value is 2 then it will set the value of currentList as -1

Then it will increment the value of currentList by 1.

After this, compiler will run the populateList() method to put data inside imageModelArrayList.

Then it will simply attach the adapter to the recycler view.

So it is all about our swipe to refresh recyclerview android example tutorial.

Swipe Down to Refresh ListView

If you want to create listview with swipe or pull down to refresh feature then read below

Источник

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