- Анимация Floating Action Button в Android
- Floating Action Button
- Меню из FAB’ов
- Creating a bubble button animation on Android
- 1) Add a button view
- 2) Create a scale animation
- 3) React to button tap
- 4) Implement the bounce interpolator
- 5) Use the bounce interpolator
- How the bounce animation interpolator works
- Reference
- Android. Добавляем анимацию к кнопкам (button)
- How to set button click effect in Android?
- 16 Answers 16
- How can I give an imageview click effect like a button on Android?
- 29 Answers 29
Анимация 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%.
Источник
Creating a bubble button animation on Android
This tutorial shows how to animate a button with bounce effect on Android using Android Studio version 2.3.
I assume that you know how to create an app in Android Studio. If you don’t have this experience yet then I would recommend reading the excellent Building Your First App tutorial from Google first.
1) Add a button view
We begin by placing a button in the activity layout file res/layout/activity_main.xml.
2) Create a scale animation
Next, we create an animation file res/anim/bounce.xml for scaling views.
- Right click on the res folder.
- Select New / Android resource file.
- Write bounce as the name of the file
- Choose the Animation resource type. The directory name field will change to anim.
Next, open the res/anim/bounce.xml file that was created for you and replace its content with the following code.
This code creates an animation that changes the size of a view from 30% to 100% during two seconds.
3) React to button tap
Now we add the code that animates the button on tap. Add the following method to your activity Java file.
If you run the app and tap the button it will animate smoothly from smaller to bigger size.
4) Implement the bounce interpolator
Next, we write the code that adds the bounce effect to the scale animation.
- Create a new Java Class file in your app module and name it MyBounceInterpolator.
- Open the Java file that was created and replace the class code with the following.
I will explain how this code works in a moment.
5) Use the bounce interpolator
Finally, open your activity Java file again and replace the entire didTapButton method with the following code.
Here we added the MyBounceInterpolator to the animation with setInterpolator method. If you run the app and tap the button it will animate with the spring effect.
How the bounce animation interpolator works
We initialized the MyBounceInterpolator object with two arguments.
- The first value 0.2 is the bounce amplitude. The higher value produces more pronounced bounces.
- The second value 20 is the frequency of the bounces. The higher value creates more wobbles during the animation time period.
In order to achieve the bounce effect the getInterpolation method maps the time using the following function:
In this equation, a and w are the amplitude and frequency values and t is the time. The equation contains a cosine function that causes the periodic wobbles during the animation. In order to reduce its amplitude with time we multiply the cosine by an exponential function. The following graph shows that the animation overshoots above the value 1 first and then settles closer to it.
Reference
- Source code for the demo Android app.
- Live graph of the time interpolator function.
- Spring button animation tutorial for iOS/Swift.
- A switch control made by Alexander Kolpakov that uses bounce interpolator.
Источник
Android. Добавляем анимацию к кнопкам (button)
20 апреля 2017 г. 2 ruslan-io 12435 android—>
Несколько простых примеров анимации кнопок (button) при нажатии в android приложении.
Сразу покажу результат данной статьи:
Если вам понравилось, то переходим к реализации.
Создаем новый проект в IDE или используем существующий.
Добавим описание анимации, для этого добавим в папку res подпапку anim (res/anim). Там будут хранится описания анимаций, добавим 4 файла (правой кнопкой мыши по папке anim, в выпадающем меню «New» => «Animation resource file»), которые будут описывать анимации:
/res/anim/alpha.xml (мерцание при нажатии):
/res/anim/rotate.xml (переварачивание при нажатии):
/res/anim/scale.xml (увелечение при нажатии):
/res/anim/anim_translate.xml (уезжает и приезжает при нажатии):
Далее в activity_main.xml (/res/layout/activity_main.xml), добавляем 4 кнопки:
И добавляем обработку нажатия по кнопкам и анимацию в MainActivity (mainActivity.java):
Готово, запускаем и наслаждаемся результатам.
Источник
How to set button click effect in Android?
In Android, when I set a background image to a button, I can not see any effect on it when it’s clicked.
I need to set some effect on the button, so the user can recognise that the button is clicked.
The button should be dark for a few seconds when it is clicked. How to do this?
16 Answers 16
This can be achieved by creating a drawable xml file containing a list of states for the button. So for example if you create a new xml file called «button.xml» with the following code:
To keep the background image with a darkened appearance on press, create a second xml file and call it gradient.xml with the following code:
In the xml of your button set the background to be the button xml e.g.
Hope this helps!
Edit: Changed the above code to show an image (YOURIMAGE) in the button as opposed to a block colour.
It is simpler when you have a lot of image buttons, and you don’t want to write xml-s for every button.
Create your AlphaAnimation Object that decides how much will be the fading effect of the button, then let it start in the onClickListener of your buttons
of course this is just a way, not the most preferred one, it’s just easier
You can simply use foreground for your View to achieve clickable effect:
For use with dark theme add also theme to your layout (to clickable effect be clear):
To make your item consistent with the system look and feel try referencing the system attribute android:attr/selectableItemBackground in your desired view’s background or foreground tag:
Use both attributes to get desired effect before/after API level 23 respectively.
Or using only one background image you can achive the click effect by using setOnTouchListener
And if you don’t want to use setOnTouchLister , the another way of achieving this is
For all the views
But for cardview which has elevation use
For Circular click effect as in toolbar
Also you need to set
This is the best solution I came up with taking hints from @Vinayak’s answer. All the other solutions have different drawbacks.
First of all create a function like this.
Explanation:
getConstantState().newDrawable() is used to clone the existing Drawable otherwise the same drawable will be used. Read more from here: Android: Cloning a drawable in order to make a StateListDrawable with filters
mutate() is used to make the Drawable clone not share its state with other instances of Drawable. Read more about it here: https://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()
Usage:
You can pass any type of View (Button, ImageButton, View etc) as the parameter to the function and they will get the click effect applied to them.
Источник
How can I give an imageview click effect like a button on Android?
I have imageview in my Android app that I am using like a button with the onClick event given, but as you might guess it is not giving imageview a clickable effect when clicked. How can I achieve that?
29 Answers 29
You can do this with a single image using something like this:
I will probably be making this into a subclass of ImageView (or ImageButton as it is also a subclass of ImageView) for easier re-usability, but this should allow you to apply a «selected» look to an imageview.
You can design different images for clicked/not clicked states and set them in the onTouchListener as follows
The better choice is that you define a selector as follows
and select the image in the event:
It’s possible to do with just one image file using the ColorFilter method. However, ColorFilter expects to work with ImageViews and not Buttons, so you have to transform your buttons into ImageViews. This isn’t a problem if you’re using images as your buttons anyway, but it’s more annoying if you had text. Anyway, assuming you find a way around the problem with text, here’s the code to use:
That applies a red overlay to the button (the color code is the hex code for fully opaque red — first two digits are transparency, then it’s RR GG BB.).
EDIT: Although the original answer below works and is easy to set up, refer to this post by an Android Developer Advocate at Google if you want / need a more efficient implementation. Also note that the android:foreground attribute is coming to all Views, including ImageView, by default in Android M.
The problem with using a selector for an ImageView is that you can only set it as the view’s background — as long as your image is opaque, you will not see the selector’s effect behind it.
The trick is to wrap your ImageView in a FrameLayout with the attribute android:foreground which allows us to define an overlay for its content. If we set android:foreground to a selector (e.g. ?android:attr/selectableItemBackground for API level 11+) and attach the OnClickListener to the FrameLayout instead of the ImageView, the image will be overlaid with our selector’s drawable — the click effect we desire!
(Note this should be placed within your parent layout.)
Источник