Android swiperefreshlayout progress position

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

Latest Update Current Stable Release Next Release Candidate Beta Release Alpha Release
July 22, 2020 1.1.0 1.2.0-alpha01

Declaring dependencies

To add a dependency on SwipeRefreshLayout, you must add the Google Maven repository to your project. Read Google’s Maven repository for more information.

Add the dependencies for the artifacts you need in the build.gradle file for your app or module:

Groovy

Kotlin

For more information about dependencies, see Add build dependencies.

Feedback

Your feedback helps make Jetpack better. Let us know if you discover new issues or have ideas for improving this library. Please take a look at the existing issues in this library before you create a new one. You can add your vote to an existing issue by clicking the star button.

See the Issue Tracker documentation for more information.

Version 1.2.0

Version 1.2.0-alpha01

androidx.swiperefreshlayout:swiperefreshlayout:1.2.0-alpha01 is released. Version 1.2.0-alpha01 contains these commits.

Bug Fixes

  • requestDisallowInterceptTouchEvent(boolean) now honors the request like any other ViewGroup. While strongly discouraged, new behavior can be disabled with setLegacyRequestDisallowInterceptTouchEventEnabled . (I968da, b/141855018)

Version 1.1.0

Version 1.1.0

androidx.swiperefreshlayout:swiperefreshlayout:1.1.0 is released. Version 1.1.0 contains these commits.

Major changes since 1.0.0

  • SwipeRefreshLayout now implements NestedScrollingChild3 and NestedScrollingParent3 .

Version 1.1.0-rc01

androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-rc01 is released with no changes since 1.1.0-beta01 . Version 1.1.0-rc01 contains these commits.

Version 1.1.0-beta01

androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-beta01 is released with no changes since 1.1.0-alpha03 . Version 1.1.0-beta01 contains these commits.

Version 1.1.0-alpha03

androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha03 is released. Version 1.1.0-alpha03 contains these commits.

Читайте также:  Hetman partition recovery для андроид

New features

  • We have a new style attribute R.styleable.SwipeRefreshLayout_swipeRefreshLayoutProgressSpinnerBackgroundColor to set the background color of the progress indicator. (aosp/931124)

API changes

  • requestDisallowInterceptTouchEvent(boolean) now always propagates up to its parents. While strongly discouraged, new behavior can be disabled with setLegacyRequestDisallowInterceptTouchEventEnabled . (aosp/1108540)

Bug fixes

  • Fixed issue with nested scrolling where SwipeRefreshLayout has a scrollable parent (e.g. ViewPager2) and a scrollable child. (b/138314213)

Version 1.1.0-alpha02

androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02 is released. The commits included in this version can be found here.

Bug fixes

  • Implemented saving and restoring of the refreshing state of SwipeRefreshLayout
  • Fixed usability bug when SwipeRefreshLayout is embedded in a RecyclerView

Version 1.1.0-alpha01

December 3, 2018

API changes

  • aosp/737631: SwipeRefreshLayout now implements NestedScrollingChild3 and NestedScrollingParent3 , enabling nested scrolling 3 parents and children to pass consumed nested scrolling distance information through SwipeRefreshLayout . If developer code currently overrides SwipeRefreshLayout.onNestedScroll(View, int, int, int, int, int) , it will likely no longer be called and SwipeRefreshLayout.onNestedScroll(View, int, int, int, int, int, int[]) should be overridden instead. Likewise, SwipeRefreshLayout.dispatchNestedScroll(int, int, int, int, int[], int) will likely no longer be called and SwipeRefreshLayout.dispatchNestedScroll(int, int, int, int, int[], int, int[]) should be overridden instead.

Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Android SwipeRefreshLayout Tutorial and Examples

SwipeRefreshLayout exists as a support library and enables us implement the now popular Swipe to Refresh.Some call it Pull To Refresh,some drag to refresh but the concept is simple,pull or swipe down on your layout and this causes display of a small progress circle.We can then of course capitalize on that and refresh our dataset.

Example 1 – Android SwipeRefreshLayout with RecyclerView -> Simulate Updates

This is a Swipe To Refresh tutorial.

We want that when the user pulls at the top of our layout we refresh data. This is a very popular technique for refreshing data that is implemented by so many mobile apps.

In this case our widget is a recyclerview.

  • Custom RecyclerView with cardviews with images and text.
  • Our data source is a simple arraylist.
  • Use SwipeRefreshlayout.
  • When user swipes down,we simulate downloading of fresh copies of data.
  • We do this in background thread using handlers.
  • Rebind the data to our recyclerview.

1. Create Basic Activity Project

  1. First create an empty project in android studio. Go to File –> New Project.
  2. Type the application name and choose the company name.
  3. Choose minimum SDK.
  4. Choose Basic activity.
  5. Click Finish.

Basic activity will have a toolbar and floating action button already added in the layout

Normally two layouts get generated with this option:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
3. MainActivity.java Class Main Activity.

In this example I used a basic activity.

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

If you’ve created yours manually then register it inside the . as following, replacing the MainActivity with your activity name:

You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

Advantage of Creating Basic Activity project

You can optionally choose empty activity over basic activity for this project.

However basic activity has the following advantages:

No. Advantage
1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
2. Provides us with appbar layout which implements material design appbar concepts.
3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
4. Decouples our custom content views and widgets from the templating features like toolbar.

Generated Project Structure

AndroidStudio will generate for you a project with default configurations via a set of files and directories.

Here are the most important of them:

No. File Major Responsibility
1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources.
2. libs/ To hold libraries we use in our project.
3. src/main/ To hold the source code of our application.This is the main folder you work with.
4. src/main/java/ Contains our java classes organized as packages.
5. src/main/res/ Contains our project resources folders as follows.
6. src/main/res/drawable/ Contains our drawable resources.
7. src/main/res/layout/ Contains our layout resources.
8. src/main/res/menu/ Contains our menu resources XML code.
9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
11. build.gradle Gradle Script used to build the android app.

2. Add Dependencies

In your build.gradle:

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

This is an example fo declarative programming.

Advantages of Using XML over Java
No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It’s easily maintanable as the user interface is decoupled from your Java logic.
3. It’s easier to share or download code and safely test them before runtime.
4. You can use XML generated tools to generate XML

Here are our layouts for this project:

(a). activity_main.xml

  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.

Here are some of the widgets, views and viewgroups that get employed»

No. View/ViewGroup Package Role
1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.

(b). content_main.xml

This layout gets included in your activity_main.xml.
We define recyclerview inside a SwipeRefreshLayout here.

(c). model.xml

RecyclerViewItem row model.

SECTION 2 : Our Data Object

Spacecraft.java

Main Responsibility : IS A SINGLE DATA OBJECT

  • Represents a single object.Here I’ll use Movie.
  • The object shall have various properties like name,image etc.
  • Each object shall occupy a specific viewitem, here cardview.

SECTION 3 : Adapter class

ItemClickListener inetrface

Main Responsibility : DEFINES ITEMCLICK EVENT HANDER SIGNATURE

  • Define our ListView ViewItem’s signature for our OnItemClick methods.

View Holder class

Main Responsibility : HOLD VIEWS FOR RECYCLING.

  • In this case textviews and imageviews.

Custom Adapter class

Main Responsibility : HELPS US BIND CUSTOM DATA TO LISTVIEW.

  • You can use one line of code to bind simple data to listview.
  • But for custom data like ours,we need an adapter to adapt it.
  • We shall use BaseAdapter as our Base class.
  • Our BaseAdapter subclass shall receive an arraylist and a context.
  • We shall simulate fetching updates.
  • We do this in background thread using Handlers.
  • Meanwhile we show a progress circle.

SECTION 4 : Our Activity

MainActivity class.

Main Responsibility : LAUNCH OUR APP.

  • We shall reference the views like ListView and Floating action button here,from our XML Layouts.Also SwipeRefreshLayout.
  • We then generate our dataset and pass it to an instance of our adapter.
  • We set the adapter to our ListView.

SECTION 5 : Our Layouts

ActivityMain.xml Layout.

  • Inflated as our activity’s view.
  • Contains xml specifications for Cordinator Layout,appbar layout,toolbar as well as floating action button.All these are contained in Design Support library.
  • Includes content main where we define our view hierarchy.

ContentMain.xml Layout.

  • Defines our view hierarchy.
  • Wraps our AdapterView with SwipeRefreshLayout.

Model.xml Layout.

  • Inflated as our AdapterView’s viewitems.
  • How our CardViews shall look.

Example 2 – Android Swipe RefreshLayout with ListView

This is an android example to swipe to refresh a custom listview ith images and text.

Swipe to Refresh or Pull to Refresh is a very popular mechanism for refeshing data. It’s also more modern than say clicking a button or something.

A special layout called SwipeRefreshLayout allows this in a very easy manner.

2. Add Dependencies

Add dependencies in your app level build.gradle.

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

This is an example fo declarative programming.

Advantages of Using XML over Java
No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It’s easily maintanable as the user interface is decoupled from your Java logic.
3. It’s easier to share or download code and safely test them before runtime.
4. You can use XML generated tools to generate XML

Here are our layouts for this project:

(a). activity_main.xml

  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.

Here are some of the widgets, views and viewgroups that get employed»

No. View/ViewGroup Package Role
1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.

(b). content_main.xml

This layout gets included in your activity_main.xml.

We define a ListView inside a SwipeRefreshLayout inside here.

(c). model.xml

Custom ListView row model:

4. Java Classes

(a). Movie.java

Our data object.

(b). ItemClickListener.java

Our Item Click Listener interface.

(c). MyViewHolder.java

Our ListView ViewHolder class:

(d). CustomAdapter.java

Our BaseAdapter class.

MainActivity.java

Example 3 – Android SQLite – RecyclerView – CRUD then Swipe To Refresh Data

Android SQLite – RecyclerView – CRUD then Swipe To Refresh Data Tutorial.

This is an android sqlite refresh tutorial with recyclerview as our adapterview.Users will swipe the recyclerview or pull it down thus refreshing data stored in sqlite database.

However first see how to perform CRUD adding data to sqlite database. Then we retrieve the data and bind to a RecyclerView.

Then when the user can show up an an input dialog and add more data. Those data don’t get shown immediately.

He can then swipe down/ or pull down the RecyclerView to refresh the data.

We use the SwipeRefreshLayout to enable this swiping functionality.

In short this is what we do in this episode 10:

  1. INSERT data to SQLite database.
  2. SELECT data from our SQLite database.
  3. Reload/Refresh data from our SQLite database when the user swipes/pulls down our RecyclerView.

SwipeRefreshLayout was introduced in Android KitKat.

1. Create Basic Activity Project

First create an empty project in android studio.You can see how to do so here.

2. Add Dependencies

Lets add dependencies in our app level build.gradle:

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

Here are our layouts for this project:

(a). activity_main.xml
  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.
(b). content_main.xml

This layout gets included in your activity_main.xml.

We wrap our RecyclerView inside a SwipeRefreshLayout:

(c). dialog_input.xml

This is the input dialog.

Users will enter data to SQLite database via this dialog.

(d). model.xml

This is our model layout.

The RecyclerView viewitems will get inflated from this template. This will happpen in our RecyclerView Adapter class.

4. Java Classes

Here are our Java Classes:

Our Data Object

(a) Spacecraft.java

This is our model class. It models a single spacecraft.

It’s our POJO class.

Our SQLite Classes

(a) Constants.java

Our database constants.

Includes sqlite database name, table name, database version, table creation statement and table dropping statements as string constants.

(b) DBHelper.java

Our database helper class.

Creates sqlite database table and upgrades it.

(c) DBAdapter.java

Our sqlite database adapter class.

Allows us perform our CRUD operations : opening database, inserting data, retrieving data, closing the database.

Our RecyclerView Classes

(a) MyHolder.java

Our RecyclerView ViewHolder class.

########(b) MyAdapter.java
Our RecyclerView Adapter class.

Our Activity class

(a) MainActivity.java

Our MainActivity class.
Will display our RecyclerView and show us a dialog for adding data to SQLite database.

Download

Download code below.

If you prefer more explanations or want to see the demo then the video tutorial is here.

No. Location Link
1. GitHub Direct Download)
2. GitHub Browse
3. YouTube Video Tutorial
4. YouTube Our YouTube Channel

report this ad

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Читайте также:  Сан андреас зомби андроид
Оцените статью