- Make a great Android UX: How to make a swipe button
- Part 1 — Let’s define our xml
- Part 2 — Starting to make a custom view
- The background
- The text
- Add the moving icon
- Add a touch listner
- Part 3 — Implementing the button login
- Movement logic
- Release logic
- expand animation
- Collapse animation
- Move the button back
- Part 4 — The result
- Анимация Floating Action Button в Android
- Floating Action Button
- Меню из FAB’ов
- Buttons
- Responding to Click Events
- Kotlin
- Using an OnClickListener
- Kotlin
- Styling Your Button
- Borderless button
- Custom background
Make a great Android UX: How to make a swipe button
Leandro Borges Ferreira
Jun 8, 2017 · 8 min read
Design not about making something beautiful, it is about making something great. You can do a great a pp by many ways, but one of my favorites is to make it the simplest and intuitive as possible, yet being original. It is important for your UI to respond to the user accordingly to importance of a certain action. Sometimes this action is too much important to be triggered by a simple click, like unlock your smartphone for example. Click in a button and receive a confirm dialog is ok. It works. But everybody does that! What can’t we make something different!?
Well, today we will.
In this tutorial I am going to show how to make a swipe button. It allows the user to make an important action without necessarily having to confirm his/her intentions, because it is hard to swipe the button by accident (But please remember: It is not impossible. So take care!). So you have a much more intuitive, nicer and simpler UX.
Cool right? So let’s go!
This tutorial is based in this repository: https://github.com/ebanx/swipe-button/ . If you prefer to just use the button, you can simply add it in your app using Gradle.
Part 1 — Let’s define our xml
Our button has a circle moving part and a rounded background. So let’s make those parts:
The circle, shape_button.xml
And the background, shape_rounded.xml
The radius can be any number that is very, so the borders are a semi-circle. You can use different colors if your prefer.
So now we have the xml that we next. Let’s start making our custom view.
Part 2 — Starting to make a custom view
We are going to extend RelativeLayout, like this:
So you must me thinking… «This is a button, why are we extending a RelativeLayout??»
As this is a complex button, we need to to add many views to be able to accomplish the behavior we need, so we need a ViewGroup. RelativeLayout is a good option because many views will overlap in this component.
We have many inner views. So let’s split this implementation in steps.
It also important for you the understand the variables of this class:
slidingButton -> This is the moving part of the component. It contains the icon.
initialX -> It is the position of the moving part when the user is going to start to move it.
active -> It is the variable that says that the button is active or not.
initialButtonWidth -> This the initial width of the moving part. We need to save it so we can morph back to the initial position.
centerText ->The text in the center of the button.
disabledDrawable / enabledDrawable -> The icons that the moving part is going to hold when the button is enabled or disabled. Use the icon that you prefer.
The background
First, we add a background
This is the view responsible to the rounded background of the button.
The text
Now we have to add a informative text in the button
This is the text in the center of the component. I am hard coding the text for simplicity, but you can use string resources for internationalization. You can add the padding that you prefer. That is the way you control the size of your component background.
Add the moving icon
This is the moving part of the component. We have to set the icons for the disabled and enabled states. Setting the padding is the way to set the size of the moving part of the component.
Add a touch listner
Add this line add the end of init method. We are going to see more about this in the next section. Then, the init is going to be:
So right now you can add this button in your app and see the result. Like this:
The button will look like this:
Ok this is looking good so far. But we not behavior yet. In the next section, you will some logic to your component!
Part 3 — Implementing the button login
Let’s implment the getButtonTouchListener.
Now we have our listener. Let’s add the logic inside the ACTION_MOVE case.
Movement logic
Let’s explain those IFs.
The first one is just to make sure that we know the initial position of the button, in case it is not zero.
The second IF is the one responsible to make the button follow the finger of the user. event.getX() returns the positions of the current touch. In this part of the code, we set the center of the button in the position of the touch and we decrease the alpha of the text as the swipe increases.
The third and the fourth IFs are responsible to set the moving part position to the limits of the component when the user swipes outside of the limits.
Release logic
In the release, we need three methods:
If the button is released and it is active, we need it to collapse. If the button is released very close to the final of the swipe, then need it to expand. If the button is release far away from the right edge, it must animate the way back.
Those are the animations:
expand animation
This animation is a bit complicated right? Don’t worry, you got this! Let me explain:
First, the slidingButton is going to animate do the left edge of our component. That’s the positionAnimator.
Second, the button must expand and occupy the entire space of the component. That the widthAnimator.
Third, we create an AnimatorSet so we can play the animations together. At the end of the animation, we set the state of the button as active and change the image of the button.
Collapse animation
This animation is similar to the expand button, but this time we increase the alpha of the text so it can become visible again.
Move the button back
This animation move the button back to the left edge and recovers the alpha of the component text.
Part 4 — The result
If you did everything right you will get this (use a dark backgound in your activity):
Источник
Анимация Floating Action Button в Android
С момента возникновения концепции Material design одним из самых простых в реализации элементов стала плавающая кнопка действия — FAB, Floating Action Button. Этот элемент быстро обрёл широчайшую популярность среди разработчиков и дизайнеров. В этой публикации мы рассмотрим, как можно анимировать FAB и сделать её интерактивной. Но сначала разберём, как вообще добавить этот элемент в ваш проект.
FAB выглядит как цветной круг в правом нижнем углу экрана. Если в Android Studio создать новый проект Blank Activity, то в нём автоматически будет сгенерирована плавающая кнопка действия.
Floating Action Button
FAB может быть одного из двух размеров: 56 dp (по умолчанию) или 40 dp. Если вы хотите подробнее изучить принципы использования FAB в дизайне приложения, то обратите внимание на официальные гайдлайны Google.
В самых свежих Android-приложениях FAB реагирует на прокручивание списка элементов. Было бы логичнее скрывать её во время прокручивания. Вот что имеется в виду:
Для отображения этой анимации создадим recyclerView , благодаря которому FAB реагирует на прокручивание. Сегодня доступно немало библиотек, позволяющих добиться этого с помощью пары строк кода. Например:
Здесь использован класс FloatingActionButton.Behavior() , чья основная задача, согласно официальной документации, заключается в перемещении видов FloatingActionButton , чтобы ни один из Snackbar их не перекрывал. Но в нашем случае этот класс является расширенным, так что мы можем его использовать для реализации нужного поведения кнопки.
Что же делает данный класс? При каждой инициализации прокрутки вниз метод onStartNestedScroll() возвращает значение true. После этого метод onNestedScroll() отображает или прячет кнопку, в зависимости от её текущей видимости. Конструктор класса FloatingActionButton.Behavior() является важной частью описанного поведения вида (view) и извлекается из XML-файла.
Добавим в FAB атрибут layout_behavior , содержащий название пакета, а в конце — имя класса. Иначе говоря, в атрибуте должно быть указано точное размещение класса в проекте. Например:
Анимация выглядит хорошо, но можно сделать ещё лучше. Например, чтобы кнопка уходила за пределы экрана во время прокрутки — это более реалистичное поведение:
Здесь используется та же логика, что и в предыдущем варианте, за исключением способа исчезновения FAB. Анимация довольно проста. Кнопка уходит вниз с помощью LinearInterpolator. Расстояние, которое ей нужно пройти, равно высоте кнопки плюс ширина нижнего поля.
Обратите внимание, что в выражениях if отсутствуют проверки View.VISIBLE и View.GONE , поскольку в данном случае вид не скрывается, а лишь уплывает за пределы экрана.
Меню из FAB’ов
Существует немало приложений, авторы которых создали красивые и хорошо работающие меню, состоящие из плавающих кнопок действия.
Давайте сделаем нечто подобное. Для начала создадим макет, содержащий три маленькие кнопки. Они невидимы и расположены в самом низу макета, под главной FAB. Содержимое fab_layout.xml:
Этот макет нужно включить в макет activity под главной FAB.
Теперь нужно добавить анимацию исчезновения и появления каждой из малых кнопок.
Примечание: здесь вы можете столкнуться с проблемой, связанной с отработкой нажатия на малые кнопки. Когда анимация завершается, реальное положение кнопки не меняется, перемещается только вид. Поэтому вы не сможете правильно обработать касание кнопки. Для решения этой проблемы можно настроить параметры макетов каждой кнопки с учётом их нового положения, и только потом выполнять анимацию перемещения вида.
Саму анимацию вы можете посмотреть в конце этой публикации. Порядок действий для всех кнопок один и тот же, различаются лишь координаты перемещения.
fab1 перемещается с помощью добавления в layoutParams полей справа и снизу, после чего инициируется анимация.
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) fab1.getLayoutParams();
layoutParams.rightMargin -= (int) (fab1.getWidth() * 1.7);
layoutParams.bottomMargin -= (int) (fab1.getHeight() * 0.25);
fab1.setLayoutParams(layoutParams);
fab1.startAnimation(hide_fab_1);
fab1.setClickable(false);
Процесс скрывания представляет собой обратное воспроизведение предыдущей анимации.
//Анимации одной из малых кнопок
Animation show_fab_1 = AnimationUtils.loadAnimation(getApplication(), R.anim.fab1_show);
Animation hide_fab_1 = AnimationUtils.loadAnimation(getApplication(), R.anim.fab1_hide);
Теперь создадим в папке res/anim/ файлы для каждой из анимаций. Делается это просто, но если у вас возникнут затруднения, то можете обратиться к документации.
Если вы посмотрите на тэг перевода (translate tag), отвечающий за движение вида, то увидите, что коэффициент перемещения (170% и 25%) соответствует коэффициентам, использованным при добавлении полей и извлечённым в Java-код.
Все вышеописанные шаги мы повторяем и для остальных малых кнопок. Различаются только коэффициенты перемещения: fab2 — 150% и 150%, fab3 — 25% и 170%.
Источник
Buttons
A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it.
Depending on whether you want a button with text, an icon, or both, you can create the button in your layout in three ways:
- With text, using the Button class:
- With an icon, using the ImageButton class:
- With text and an icon, using the Button class with the android:drawableLeft attribute:
Key classes are the following:
Responding to Click Events
When the user clicks a button, the Button object receives an on-click event.
To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
For example, here’s a layout with a button using android:onClick :
Within the Activity that hosts this layout, the following method handles the click event:
Kotlin
The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:
- Be public
- Return void
- Define a View as its only parameter (this will be the View that was clicked)
Using an OnClickListener
You can also declare the click event handler programmatically rather than in an XML layout. This might be necessary if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.
To declare the event handler programmatically, create an View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener) . For example:
Kotlin
Styling Your Button
The appearance of your button (background image and font) may vary from one device to another, because devices by different manufacturers often have different default styles for input controls.
You can control exactly how your controls are styled using a theme that you apply to your entire application. For instance, to ensure that all devices running Android 4.0 and higher use the Holo theme in your app, declare android:theme=»@android:style/Theme.Holo» in your manifest’s element. Also read the blog post, Holo Everywhere for information about using the Holo theme while supporting older devices.
To customize individual buttons with a different background, specify the android:background attribute with a drawable or color resource. Alternatively, you can apply a style for the button, which works in a manner similar to HTML styles to define multiple style properties such as the background, font, size, and others. For more information about applying styles, see Styles and Themes.
Borderless button
One design that can be useful is a «borderless» button. Borderless buttons resemble basic buttons except that they have no borders or background but still change appearance during different states, such as when clicked.
To create a borderless button, apply the borderlessButtonStyle style to the button. For example:
Custom background
If you want to truly redefine the appearance of your button, you can specify a custom background. Instead of supplying a simple bitmap or color, however, your background should be a state list resource that changes appearance depending on the button’s current state.
You can define the state list in an XML file that defines three different images or colors to use for the different button states.
To create a state list drawable for your button background:
- Create three bitmaps for the button background that represent the default, pressed, and focused button states.
To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-patch bitmaps.
Источник