Android floating action button icon color

How to Change Icon Color of Floating Action Button in Android?

Kotlin Android – Change Icon Color of Floating Action Button

To change icon color of Floating Action Button in Kotlin Android we have to set the tint attribute (in layout file) or imageTintList parameter (in Kotlin program) of FAB with the required color.

To change the icon color of Floating Action Button in layout file, set the app:tint attribute with the required color value as shown in the following code snippet.

To change the icon color of Floating Action Button dynamically or programmatically in Kotlin activity file, set the imageTintList parameter of the FAB with the required color value as shown in the following code snippet.

Example – Change Icon Color of FAB via Layout File

Create an Android Application with Empty Activity and modify the activity_main.xml with the following code.

activity_main.xml

Run this Android Application, and we would get the output as shown in the following screenshot, with the color of icon in Floating Action Button (FAB) changed to the given color value of #E91E63 .

Example – Change Icon Color of FAB Programmatically

Create an Android Application with Empty Activity and modify the activity_main.xml and MainActivity.kt with the following code.

activity_main.xml

MainActivity.kt

Run this Android Application, and we would get the output as shown in the following screenshot, with the icon color of Floating Action Button (FAB) changed to the given color value of Color.rgb(255, 50, 50) .

Conclusion

In this Kotlin Android Tutorial, we learned how to change the background color of Floating Action Button (FAB) widget via layout file or programmatically in Kotlin Activity file, with examples.

Источник

Добавляем Floating Action Button в свое Android приложение

В этом году на презентации Google I/O был представлен новая версия Android — L. Вместе с этим было представлено много новых плюшек для пользователей и разработчиков. Но одним из главных новшеств, несомненно, было новое решение Google для унификации дизайна — Material Design.

Одним из паттернов Material Design является Floating Action Button.

Читайте также:  Камера заднего вида как регистратор андроид

Что такое Floating Action Button ?

Google говорит, что это «специальный метод для способствования действию». Сама же кнопка имеет форму круга, плавающего над интерфейсом.

Стоит отметить, что Floating Action Button должна отражать только главное действие в приложении.

Быстрая и грязная реализация

Я хотел создать быстрый способ добавления простейшей FAB для своих Android приложений с minSdkVersion = 14 (Ice Cream Sandwich). Я также реализовал анимацию появления/исчезновения и небольшие возможности для кастомизации кнопки.

Весь код доступен в Github Gist (добавьте этот класс в свой проект).

При создании кнопки в XML, я обнаружил некоторые трудности позиционирования View у нашей кнопки над остальными View (в частности, над Navigation Drawer). Я решил реализовать кнопку программно и работать посредством Builder-паттерна, что позволит размещать FAB выше других View в Activity при вызове .create().

Отлично! Но как мне добавить это в свое приложение ?

Добавить Floating Action Button очень даже просто:

Размер кнопки легко изменить посредством вызова .withButtonSize(int size). По умолчанию стоит 72dp.

Заключение

Похоже, что Google будет использовать этот паттерн во многих своих приложениях. И еще до сих пор нет никаких новостей о том, будет ли Google добавлять floating action button в support library, поэтому пока что не стесняйтесь использовать это решение.

Источник

Анимация 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%.

Источник

How to add Extended Floating Action Button in Android | Android Studio | Java

How to add Extended Floating Action Button in Android | Android Studio | Java.

In this tutorial, we are going to create an extended floating action button in android. A floating action button (FAB) performs the primary, or most common, action on a screen. It appears in front of all screen content, typically as a circular shape with an icon in its center.

Extended Floating Action Button is the newly introduced class with Material Components library in Android.

Material Components is introduced with SDK 28 or Android P. It’s a superset of Support Design Library with lots of new additions and improvements. And, in this tutorial, we are going to create an extended floating action button.

So, let’s start creating the extended FAB.

Before going to create let’s see what you’re going to see.

Step 1: add the dependency

make sure to add the material design dependency in your build.gradle app file.

Step 2: add the drawable files

before going to design the main XML file, first, import the drawable files. Below drawable files that I used in my project.

Step 3: design the XML file

now, design the main XML file, add the Extended Floating Action Button that is set as the parent FAB and also add the child FAB. Here as a child FAB, I used two FABs.

Читайте также:  Продлить лицензию для касперского для андроид

parent FAB: Action

child FAB 1: Alarm

child FAB 2: Person

Step 4: add the functionality

now in the main JAVA file add the functionality for the extended FAB and add the click listener in the child FAB.

Источник

How can I change the floating action menu icon? #295

Comments

thanos1983 commented Apr 28, 2016 •

I have tried to add the fab:fab_icon just like on floating buttons, but it does not seem to work. Is there any way to change the background image on the floating menu also, except the buttons?

Thank you in advance for your time and effort.

The text was updated successfully, but these errors were encountered:

markvankleef commented Apr 29, 2016

For the icon you just need to set android:src=»» filled with a drawable

thanos1983 commented Apr 29, 2016

I did also tried that, but it did not work. 🙁 Thanks for your time and effort though. 😀

rohitkeshwani07 commented May 16, 2016

+1 to @thanos1983 . did u find the answer?

thanos1983 commented May 16, 2016 •

I do not have a solid solution to my problem but I have created a work around. Because the answer is big to rewrite it I will provide a link in case that someone in the future might have the same problem How to set icon to getbase FloatingActionsMenu. I have also found a solution in order to update the menu icon from the «sub buttons» when they are clicked Change image Floating Action Button Android

I hope this helps somebody else that had the same problem. If you have any queries or my answer is not complete get back to me and I will try to help you.

ibnouf88 commented May 17, 2016

Please use:
.
android:src=»@android:drawable/ic_menu_share»
.
Don’t use «fab:icon. «, but instead use «android:src. »
It works for me 👍
X5ibnouf

thanos1983 commented May 18, 2016

I just tried it, and for me is not working. I do not know if it it not working because I have modified the library or it does not work generally. But the solution that I have posted it works just fine for me. 😀

Maybe someone else can tested and verify that it works.

Ostkontentitan commented Jun 9, 2016 •

i can confirm that «android:src» has no effect.

toanvc commented Jun 25, 2016

Trying this library, you can use custom icon for menu button by using:
fab:fab_menuIcon=»@drawable/myIcon»

noman404 commented Aug 26, 2016

if you are using the source not gradle lib then use his changes to the sources.

ghost commented Apr 4, 2017 •

I am also not getting menu icon using android:src=»@drawable/*» and using com.getbase:floatingactionbutton:1.10.1 included in gradle as of @Ostkontentitan

williamsiuhang commented Sep 27, 2017

For the menu icons I ended up doing it in Java:

I also downloaded the library to use in my project locally, not sure if that makes a difference.

akshkdm commented Sep 11, 2018

using this library
com.github.clans.fab.FloatingActionMenu

app:menu_icon=»@drawable/ic_share»
above solution worked for me.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

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