Swiping buttons in android

Zen Android

Zen Android

Hello and welcome to Zen Android, a blog about programming in general and Android in particular.

  • Linkedin
  • Github
  • Stack Overflow
  • Facebook
  • RSS

Android Gesture Detection and Animations: creating a Swipe Button control

In this article we’re going to look at how to create a production-grade Swipe Button control that has the following features:

  1. tracks the finger with a transparent overlay
  2. supports flinging
  3. animates to a complete state
  4. moves right while swiping and also causes other content on the screen to move creating a parralax effect
  5. shakes when tapped so that it hints to the user that it needs to be swiped to activate
  6. has a slide-out animation

The code is available in this repo and a short capture of the result can be seen below:

The plan

To start things off we’re going to create a custom view, but we’re not going to be extending View and drawing it from scratch. While that alternative may seem tempting, it would be very difficult to modify later down the line if the design changes. I instead opted to extend a FrameLayout and place several Views and TextView items inside it to give the general look and feel of the swipe button.

In order to animate other items on the screen (such as for example the grey CardView in the GIF above) we’re going to publish an observable that produces a float between 0 (initial state) and 1 (fully swiped state). The enclosing activity can then orchestrate the other views on the screen to move in tandem with our swipe button. A second observable is going to notify the activity when the swiping gesture is performed and the animations have ended. Please note that I am using RxJava observables but you could easily use listeners for the same effect and a more «oldschool» approach.

We’re going to employ a GestureDetector to determine when the user swipes, taps or flings over the button. We’re going to also use the design library’s FlingAnimation object to provide a realistic behavior when «flinging».

Library roundup

The library section in the gradle file contains the usual suspects:

The only thing that is somewhat rarer here is the Dynamic Animation Library. This library contains a couple of useful physics based animations, such as FlingAnimation and SpringAnimation .

The layout

I decided to go with a very flat layout with the different components stacking on top of eachother. The «button» part is a View, as is the white overlay that come on top of it. Between them we have a TextView that holds the text. Finally, the checkmark that appears when the swipe is complete sits on top of everything but is initially transparent.

Gesture detection

For gesture detection we’re going to go with the GestureDetector class. This is part of the Android package, but is less known. The way it works is that you instantiate it and forward it all the touch events and it provides a set of events you can listen to — such as onScroll , onFling etc.

Читайте также:  Usb камера для android устройств

We’ll be hooking up into the onScroll to provide feedback for the swiping progress, onSingleTapUp to make the button shake and onFling to animate the flinging gesture. As you can see we also hook up manually on the event of the user raising their finger since there is no equivalent gesture in the detector.

Dragging progress

The position of the button, the width and opacity of the white overlay and the transparency of the text (in effect pretty much all the state) is controlled by a single variable that takes the values between 0 and the width of the entire layout. We also have a triggered boolean that disables all animations and touch events once the swipe is complete. Let’s have a look at the function that accomplishes this.

We achieve the move to the right of the entire layout by adding a padding to the left (and removing the same value from the right). We then compute the state of the subcomponents based on the progress value. What’s left is to add the code to call this method when the user drags the finger over the layout (the onScroll method from the GestureDetector ):

Handling the end of the drag

When the user finishes the dragging process (without flinging) the GestureDetector does not offer any callbacks. We do have the option of handling it ourselves inside the onTouchEvent method. The way the completed method looks is:

Based on the x coordinate of where the user released the drag event we then compute if the drag resulted in an activation of the button or not. In case it did, we animate the progress variable to the end state, then set the triggered flag and animate to the progress back to start (to reset the padding) while also fading in the checkmark. In case it was not above the threshold, we animate the progress variable directly to the start state.

Handling the flinging gesture

Flinging is when a user quickly swipes the finger over the layout without moving all the way to the right. We want the movement of the white overlay to continue with some approximation of inertia before coming to a stop, kinda like throwing something along an abrasive surface. This behaviour is achieved by use of the FlingAnimation class in this manner:

Note that we’re reusing the setDragProgress and onDragFinished methods discussed above to act «as if» the user would continue the dragging process.

Shake on tap

If we want the button to shake on tap, we can use the GestureDetector method onSingleTapUp event and animate the padding between several values. Please note the less common use of the varargs version of the factory method for the ValueAnimator that causes the padding to go from 0 to the max amplitude then back to 0 then half the amplitude, then to 0 again then to a quarter amplitude and then end up in 0. We also use an AccelerateDecelerateInterpolator to give the animation a more natural look.

Publishing updates

In order for the activity to coordinate other views with the swiping of the button we publish two observables: one with the progress variable (normalized between 0 and 1) and one with an event for when the button is triggered and the animations finish. We achieve this with the following code:

Then, in the MainActivity we can add code such as:

Читайте также:  Make notes on android

Note that in order to achieve the parralax effect the amplitude of the translation of hte card container should be smaller than the one for the button itself.

Putting it all together

Here is the entire code of the SwipeButton. A sample project can be found in the repo.

Conclusion

In this article we looked at how we can implement production-grade animation and gestures in Android. I hope it encourage you guys to try and experiment with more interactive views and transitions. I think there is a misconception that Android does not really support this sort of thing and I hope I managed to dispel that a little.

Источник

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) , чтобы начать смахивание вручную.

Читайте также:  Ottplayer 4pda android tv box

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

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

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

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

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

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

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

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

Заключение

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

Исходный код

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

Источник

Swiping buttons in android

Library of an android button activated by swipe.

  • Easy to use.
  • Makes your app look great
  • Better UX in sensitive button

Add the button in your layout file and customize it the way you like it.

Setting the sliding button size

You can set the size of the moving part of the button by changing the app:button_image_width and app:button_image_height properties.

Setting the text part size

You can set the size of the fixed part of the button by setting the text size of the setting the padding in this part.

Listening for changes

You can set a listener for state changes

Or listen for the activation of the button

  • button_image_width: Change the width of the moving part of the button
  • button_image_height: Change the height of the moving part of the button
  • inner_text: Text in the center of the button. It disapears when swiped
  • inner_text_color: Color of the text
  • inner_text_size: Size of the text
  • inner_text_[direction]_padding: Sets the padding of the text inside the button. You can set how big this part of the button will by setting text size and padding.
  • button_image_disabled: Icon of the button when disabled. This is the initial state.
  • button_image_enabled: Icon of the button when disabled. This is the initial expanded state.
  • button_[direction]_padding: Sets the padding of the button the slide with the touch. You can set how big the button will be by setting the image and the padding
  • initial_state: Initial state. Default state is disabled.
  • has_activate_state: Set if the button stops in the «active» state. If false, the button will only come back to the initial state after swiped until the end of its way. Use OnActiveListener if you set the parameter to false.
  • button_trail_enabled: Set trailing effect enabled.
  • button_trail_drawable: Set the color of the trailing effect.

If you would like to see a front-end version of this button you can check a codepen in this link:

Bugs and features

For bugs, feature requests, and discussion please use GitHub Issues.

Источник

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