Swipe views in android

How to create Swipe Navigation in an Android App

When talking about Android Apps, the first thing that comes to mind is variety. There are so many varieties of Android apps providing the user with beautiful dynamic UI. One such feature is to navigate in our Android Apps using left and right swipes as opposed to clicking on buttons. Not only does it look more simple and elegant but also provides ease of access to the user. There are many apps which use this swipe feature to swipe through different activities in the app. For example, the popular chatting app, Snapchat, uses it to swipe through lenses, chats and stories. Here, we will learn how to implement swipe views in our own Android app.

We can implement this by use of two features:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

  1. Fragments A fragment is just a part of an activity. We can have a fragment that takes up part of a screen or a whole screen. Or we can show multiple fragments at the same time to make up a whole screen. Within an activity, we can also swap out different fragments with each other.
  2. ViewPager ViewPager is a class in Java which is used in conjunction with Fragments. It is mostly used for designing the UI of the app.

How does it work?
First we need to set an adapter on the ViewPager using the setAdapter() method. The adapter which we set is called FragmentPagerAdapter which is an abstract class in Java. Hence, we create our own SampleFragmentPagerAdapter which extends from FragmentPagerAdapter and displays our Fragments on the screen. When we launch the app in our device, the ViewPager asks the SampleFragmentPagerAdapter how many pages are there to swipe through. The getCount() method of the adapter returns this answer to the ViewPager. Then the ViewPager asks for the Fragment which is at the 0th position and the adapter returns that particular fragment which is then displayed by ViewPager on our screen. When we swipe left, ViewPager asks adapter for the Fragment at 1st position and similarly, it is displayed on the screen and it continues so on.

Step by step implementation:
We will be creating three fragments that is three screens that the user can swipe through. Then we will add these fragments to our FragmentPagerAdapter and finally set it on ViewPager.
Note: To run these codes, you need to copy and paste them in Android Studio as it won’t run on the IDE!

Step1: Creating Fragments:
To create a fragment, click on app > Java > com.example.android(Right Click) > New > Fragment > Fragment(Blank)

We can create as many Fragments as we want but since we will be displaying only three screens, hence we will create three Fragments.
Now we will open our Fragments and copy this code over there:

Читайте также:  Как настроить андроид самсунг по умолчанию

Источник

Drag и Swipe в RecyclerView. Часть 1: ItemTouchHelper

Существует множество обучающих материалов, библиотек и примеров реализации drag & drop и swipe-to-dismiss в Android c использованием RecyclerView. В большинстве из них по-прежнему используются устаревший View.OnDragListener и подход SwipeToDismiss, разработанный Романом Нуриком. Хотя уже доступны новые и более эффективные методы. Совсем немногие используют новейшие API, зачастую полагаясь на GestureDetectors и onInterceptTouchEvent или же на другие более сложные имплементации. На самом деле существует очень простой способ добавить эти функции в RecyclerView . Для этого требуется всего лишь один класс, который к тому же является частью Android Support Library.

ItemTouchHelper

ItemTouchHelper — это мощная утилита, которая позаботится обо всём, что необходимо сделать, чтобы добавить функции drag & drop и swipe-to-dismiss в RecyclerView . Эта утилита является подклассом RecyclerView.ItemDecoration, благодаря чему её легко добавить практически к любому существующему LayoutManager и адаптеру. Она также работает с анимацией элементов и предоставляет возможность перетаскивать элементы одного типа на другое место в списке и многое другое. В этой статье я продемонстрирую простую реализацию ItemTouchHelper . Позже, в рамках этой серии статей, мы расширим рамки и рассмотрим остальные возможности.

Примечание. Хотите сразу увидеть результат? Загляните на Github: Android-ItemTouchHelper-Demo. Первый коммит относится к этой статье. Демо .apk -файл можно скачать здесь.

Настройка

Сперва нам нужно настроить RecyclerView . Если вы ещё этого не сделали, добавьте зависимость RecyclerView в свой файл build.gradle .

ItemTouchHelper будет работать практически с любыми RecyclerView.Adapter и LayoutManager , но эта статья базируется на примерах, использующих эти файлы.

Использование ItemTouchHelper и ItemTouchHelper.Callback

Чтобы использовать ItemTouchHelper , вам необходимо создать ItemTouchHelper.Callback. Это интерфейс, который позволяет отслеживать действия перемещения (англ. move) и смахивания (англ. swipe). Кроме того, здесь вы можете контролировать состояние выделенного view -компонента и переопределять анимацию по умолчанию. Существует вспомогательный класс, который вы можете использовать, если хотите использовать базовую имплементацию, — SimpleCallback. Но для того, чтобы понять, как это работает на практике, сделаем всё самостоятельно.

Основные функции интерфейса, которые мы должны переопределить, чтобы включить базовый функционал drag & drop и swipe-to-dismiss:

Мы также будем использовать несколько вспомогательных методов:

Рассмотрим их поочередно.

ItemTouchHelper позволяет легко определить направление события. Вам нужно переопределить метод getMovementFlags() , чтобы указать, какие направления для перетаскивания будут поддерживаться. Для создания возвращаемых флагов используйте вспомогательный метод ItemTouchHelper.makeMovementFlags(int, int) . В этом примере мы разрешаем перетаскивание и смахивание в обоих направлениях.

ItemTouchHelper можно использовать только для перетаскивания без функционала смахивания (или наоборот), поэтому вы должны точно указать, какие функции должны поддерживаться. Метод isLongPressDragEnabled() должен возвращать значение true , чтобы поддерживалось перетаскивание после длительного нажатия на элемент RecyclerView . В качестве альтернативы можно вызвать метод ItemTouchHelper.startDrag(RecyclerView.ViewHolder) , чтобы начать перетаскивание вручную. Рассмотрим этот вариант позже.

Чтобы разрешить смахивание после касания где угодно в рамках view -компонента, просто верните значение true из метода isItemViewSwipeEnabled() . В качестве альтернативы можно вызвать метод ItemTouchHelper.startSwipe(RecyclerView.ViewHolder) , чтобы начать смахивание вручную.

Следующие два метода, onMove() и onSwiped() , необходимы для того, чтобы уведомить об обновлении данных. Итак, сначала мы создадим интерфейс, который позволит передать эти события по цепочке вызовов.

Самый простой способ сделать это — сделать так, чтобы RecyclerListAdapter имплементировал слушателя.

Очень важно вызвать методы notifyItemRemoved() и notifyItemMoved() , чтобы адаптер увидел изменения. Также нужно отметить, что мы меняем позицию элемента каждый раз, когда view -компонент смещается на новый индекс, а не в самом конце перемещения (событие «drop»).

Теперь мы можем вернуться к созданию SimpleItemTouchHelperCallback , поскольку нам всё ещё необходимо переопределить методы onMove() и onSwiped() . Сначала добавьте конструктор и поле для адаптера:

Читайте также:  Android play store google account

Затем переопределите оставшиеся события и сообщите об этом адаптеру:

В результате класс Callback должен выглядеть примерно так:

Когда Callback готов, мы можем создать ItemTouchHelper и вызвать метод attachToRecyclerView(RecyclerView) (например, в MainFragment.java):

После запуска должно получиться приблизительно следующее:

Заключение

Это максимально упрощённая реализация ItemTouchHelper . Тем не менее, вы можете заметить, что вам не обязательно использовать стороннюю библиотеку для реализации стандартных действий drag & drop и swipe-to-dismiss в RecyclerView . В следующей части мы уделим больше внимания внешнему виду элементов в момент перетаскивания или смахивания.

Исходный код

Я создал проект на GitHub для демонстрации того, о чём рассказывается в этой серии статей: Android-ItemTouchHelper-Demo. Первый коммит в основном относится к этой части и немного ко второй.

Источник

Tek Eye

This introductory tutorial shows how to code a simple page swiping app with the ViewPager class. It is the basis for more complex view flipping examples, such as an image swiping gallery (to replace the Android Gallery widget that was deprecated in API 16). The ViewPager controls the swiping (flicking the screen left and right) between multiple screens or pages of data.

(This Android ViewPager swipe tutorial assumes that Android Studio is installed, a basic App can be created and run, and the code in this article can be correctly copied into Android Studio. The example code can be changed to meet your own requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter.)

Simple Flip View Tutorial Using ViewPager for the Android Screen Swipe Effect

The ViewPager is fed with the multiple screens by a PagerAdapter (or the sub-classes FragmentPagerAdapter and FragmentStatePagerAdapter ).

The implementation of the PagerAdapter will create (and destroy) the pages to be shown in the ViewPager. It will load the pages with the data (such as text or images) that must be displayed on the individual pages. This tutorial’s PagerAdapter allows swiping through a series of strings (text). The following steps are performed to complete the screen swiping demo:

  • Start a new Android app in Android Studio.
  • Add the ViewPager widget to the app’s screen.
  • Define the data (text) to be displayed on each swiped page.
  • Define the layout for the swiped pages.
  • Implement PagerAdapter which will create each page and load it with data.
  • Test the app.

Start a New Android App

Start this tutorial by generating a new project in Android Studio, here it is called it Swipe Demo. (Alternatively add the page swiping effect to an existing App.) Use an Empty Activity with other settings left at default values. Update: The minimum Android API required for the ViewPager Support Library is now API level 9 (Gingerbread), or API level 14 (Ice Cream Sandwhich) if developing apps using Google AdMob for advertising.

The Support Library

The ViewPager is part of the Support Library. If not installed use the SDK Manager to download it (scroll to the bottom of the list of items in SDK Manager to find the Android Support Repository). See also Support Library Setup on the Android Developers website.

Adding the ViewPager Widget to the App’s Layout

The ViewPager is referenced using it’s package name of android.support.v4.view.ViewPager. (The v4 stands for the first API version that the original Support Library could be used on, but now it requires API level 9 or later.)

Here’s the layout from this demo referencing the ViewPager. It is a RelativeLayout with a ViewPager below a TextView . Replace the activity_main.xml with code similar to this:

Defining the Data to Show on Each ViewPager Page

In this example some text is shown on each swiped page. Here the strings are stored in an array. The array could be defined in code but here they are in a resource file. Open the strings.xml file and add a string array. We are using the code names for Android version releases, all named after desserts. Here is the strings.xml for the Swipe Demo:

In the main class file, here called MainActivity.java, a string array is declared at the class level, String pageData[], and loaded from the resource in the onCreate method using pageData=getResources().getStringArray(R.array.desserts).

Create a Layout Used for the Swiped Pages

The swiped screen will display large text that has been centered. Using the Project explorer select the layout folder. Using the context menu (usually right-click) or the File menu select New. Then select Layout resource file. Enter the File name of page.xml. Enter RelativeLayout for the Root element, this will hold the centered text data. Click OK then add a TextView with the textAppearance attribute set to AppCompat.Large, give it an id of textMessage. The final layout XML for a page will be similar to this:

Читайте также:  Пеший туризм навигатор для андроид

Implement PagerAdapter in the Java Class

The PagerAdapter will create and destroy the pages being swiped. In the MainActivity.java class, before the closing brace, create a new class, e.g. MyPagesAdapter, it needs to extend PagerAdapter and will require android.support.v4.view.PagerAdapter to be added to the imports. The new class implements four methods:

  1. getcount() – Returns the total number of pages and here it is simply the number of strings in the array so returns pageData.length.
  2. instantiateItem() – This is passed a reference to the ViewPager so the new page can be added to it, and the page number so that the correct data for the page can be loaded. In our implementation we use a class level LayoutInflater to create an instance of page.xml, and set the TextView to a string in the pageData array.
  3. isViewFromObject() – A method required by the ViewPager to check that a page matches the object from which it was created.
  4. destroyItem() – This is called when the ViewPager no longer requires the page (it is now several swipes away so can be cleared).

Here is the full MainActivity Java class with the PagerAdapter implemented:

The source code is also available in the text_swiper.zip file ready to import into Android Studio (also available from the Android Example Projects page).

Test the Swiping by Running the App

This simple swiping App can be extended to support different types of data.

See Also

Archived Comments

Ahmad on September 4, 2014 at 3:04 am said: Very useful and detailed. Thank you very much!

Dewan on July 14, 2015 at 6:23 am said: It’s so perfect! Thank you. This is helping me a lot.

Aelafseged on August 11, 2015 at 11:25 am said: So neat and to the point. I salute you for your Javaness.

Raul on November 9, 2015 at 8:47 pm said: Thank you very much! This is the first example that is simple and actually works!

Muhammad Mubeen on February 14, 2016 at 9:45 am said: How to create multiple swipe view? Can anyone help me please?

Christopher Geel in January 2018 said: Thanks buddy! This worked 100%

Author: Daniel S. Fowler Published: 2013-06-03 Updated: 2017-04-24

Do you have a question or comment about this article?

(Alternatively, use the email address at the bottom of the web page.)

↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.

Free Android Projects and Samples:

Источник

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