- Android. Добавляем анимацию к кнопкам (button)
- Анимация 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
- Creating a beautiful Button: Android
- Choosing Colors
- Creating Gradients
- Creating a Selector
- Declare a style for button
- Try it!!
- What about Ripple?
- Button effects in android
- Adding Button to Layout
- Button Attributes
- Enabling and disabling Button
- Button Drawable
- Android Image Button
- Xml drawable selector example
- Handling Button Clicks
- Android Button Design and Styles
- Button Styles Customization
- Rounded Corner Button
- Button Elevation and Shadow
- Button Shadow Animation Customization
- About
Android. Добавляем анимацию к кнопкам (button)
20 апреля 2017 г. 2 ruslan-io 12449 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):
Готово, запускаем и наслаждаемся результатам.
Источник
Анимация 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.
Источник
Creating a beautiful Button: Android
Oct 4, 2019 · 3 min read
Creating a custom Button from scratch.
This article will be a quick one, to demonstrate how can you create a Button in Android effectively. We’ll do it in a concise way so that lots of xmls are not spread across App. Lets start without wasting time.
Choosing Colors
Creating Gradients
We will create 2 gradients one for default and one for pressed state. Lets create one reverse of other.
Creating a Selector
This is where your press and default state will be defined.
Declare a style for button
Declaring in styles in such a way that even if we drag a button from component palette it must be our button. Next step is to declare button in layout and check our progress.
Try it!!
Possible result can be seen without running our application. We need some padding and button text to be white. Lets quickly update this in styles.
That’s great progress. Our Button is supported to most of the phones with API KitKat and above(As it was the lowest API selected when created project).
What about Ripple?
Ripples are modern requirement and adds more sugary effect on button feed back. So next we will go ahead and wrap our button with ripple and when prompted with error we will create one more button_selector for API v21 and above.
Lets first create a ripple color.
We have finally reached to our end state of designing button. This is the most affordable way to create a button where one have total control over it. Do you think it is too much to create a button? Well it is worth investing. Once a button like this is created and declared in style any developer when creating a layout will not have to worry about styling a button. And the button dragged and dropped in layout will be a branded one.
I told you there will be less XMLs. So once you have a good hands on and you have created couple of buttons, you may club together some xmls to create one file and rest is past.
Design, so that you design something new next time
Источник
Button effects in android
September 06, 2017
One of the important UI components in applications is Button. Button can be used to provide actions for user to perform and attach user events to back end behavior.
This post gives details about using and styling android button with examples.
Adding Button to Layout
Android user interface is defined in layout xml file. You can add Button element and set attributes to xml manually. Or using android studio layout design tool, you can add button component from palette to layout and set attributes.
Button Attributes
Button is a subclass of TextView and inherits attributes from TextView and View classes. Below are some of the important button attributes which can be used to defined desired button look and behavior.
- background : to set background to either color or a drwable.
- onClick : to set method that needs to be run when a button is clicked.
- minHeight : to define minimum height of button
- minWidth : to define minimum width of button.
- stateListAnimator : to define animation when button state changes.
- focusable : to indicate whether keystroke should work
- clickable : to indicate whether button is clickable or not
- gravity : to set button text alignment.
- textAppearance : to set text style.
Enabling and disabling Button
You can use enabled attribute to enable and disable button by setting it to true or false. A button can be enabled or disabled in program by calling setEnabled method as shown below.
Button Drawable
You can make button display image and text using drawableTop, drawableBottom, drawableRight, and drawableLeft attributes below screen shot shows output of setting them.
Android Image Button
Android provides ImageButton which can be used to make an image as button. To set an image, you can use src attribute of ImageButton. You can even use different images to be shown in different button states by defining xml drawable selector as shown below.
Xml drawable selector example
Handling Button Clicks
Button clicks can be handled in two ways. First one is by setting onClick attribute of Button in layout xml. Second one is by assigning on click listener to button in activity or fragment.
To set onClick attribute, first define a public void method with View as argument in activity or fragment and use the method name as value to set onClick attribute as shown below.
Below code shows handling button clicks using on click listener.
Android Button Design and Styles
You can apply styles and themes to change look and feel of buttons. Android platform provides pre-defined material styles. Read material styles and compatibility post to learn about android material styles. Below screen shot shows buttons styled with different material styles.
Applying theme or style to button.
Button Styles Customization
You can change the default colors of material styles applied to button by setting colorAccent attribute at application level and colorButtonNormal attribute at widget level to the desired colors. Attribute colorControlHighlight is used to set color for button when it is in pressed state.
Once you define custom style, you can apply it to buttons using theme attribute. Below is an example of custom theme.
Rounded Corner Button
You can define inset as shown below to create rounded corner button and save the drwable xml in res/drawable folder. You can increase or decrease corners element’s radius attribute to adjust button corner radius.
Then define style setting the background attribute to the xml drawable and apply it to button using style attribute.
Button Elevation and Shadow
You can set elevation and translationZ attributes to draw shadow of button.
Button Shadow Animation Customization
You can define different shadow properties for different states of button and animate the transition by defining selector. You can apply the animator to button using stateListAnimator property.
Notice that stateListAnimator set to null in the above (elevation and translationZ) example. This was done to remove default animator applied using stateListAnimator attribute in material themes for button. In order for elevation and translationZ to work, stateListAnimator needs to be set to null.
To customize the animation, meaning animating shadow transition between button states, you need to define selector as shown below in res/animator folder and set stateListAnimator property of custom theme to the defined animator.
Below is an example of state animator.
Apply the below custom theme, which is using state animator, to a button using style or theme attribute.
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник