- How to Change Icon Color of Floating Action Button in Android?
- Kotlin Android – Change Icon Color of Floating Action Button
- Example – Change Icon Color of FAB via Layout File
- Example – Change Icon Color of FAB Programmatically
- Conclusion
- [FloatingActionButton] FAB Icon is Always Black #1106
- Comments
- HeyItsMedz commented Mar 11, 2020
- Floating Action Buttons
- Добавляем Floating Action Button в свое Android приложение
- Что такое Floating Action Button ?
- Быстрая и грязная реализация
- Отлично! Но как мне добавить это в свое приложение ?
- Заключение
- How can I change the floating action menu icon? #295
- Comments
- thanos1983 commented Apr 28, 2016 •
- markvankleef commented Apr 29, 2016
- thanos1983 commented Apr 29, 2016
- rohitkeshwani07 commented May 16, 2016
- thanos1983 commented May 16, 2016 •
- ibnouf88 commented May 17, 2016
- thanos1983 commented May 18, 2016
- Ostkontentitan commented Jun 9, 2016 •
- toanvc commented Jun 25, 2016
- noman404 commented Aug 26, 2016
- ghost commented Apr 4, 2017 •
- williamsiuhang commented Sep 27, 2017
- akshkdm commented Sep 11, 2018
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.
Источник
[FloatingActionButton] FAB Icon is Always Black #1106
Comments
HeyItsMedz commented Mar 11, 2020
For some reason when I set an icon using android:src on a FAB, it will force the icon to be black rather than whatever colour the (vector) icon actually is. The issue popped up once I upgraded from 1.0.0 to 1.1.0, and can be seen directly from the XML layout preview. Using android:tint does not resolve the issue
Unfortunately I’m also relying on a bug fix in 1.1.0 for another component, so it’s not like I can revert back to 1.0 and call it a day
I tried to see if the issue still occurred if I opened a new application from Android Studio. Interestingly, the icon will stay black if app theme’s parent is set to Theme.MaterialComponents.Light but shows correctly if changed to Theme.AppCompat.Light
Source code
This can be reproduced by opening a new project in Android Studio, choosing the Empty Activity option.
Set the AppTheme parent to Theme.MaterialComponents.Light , and change the generated activity_main.xml to this:
ic_arrow_forward_white_24dp.xml (this is generated as a Vector Asset within Android Studio):
Switching com.google.android.material:material version between 1.0.0 and 1.1.0 will show the icon changes colour
Material Library version:
1.0.0: Works correctly
1.1.0-alpha01: Does not work as expected
1.1.0: Does not work as expected
1.2.0-alpha05: Does not work as expected
I hope that helps! Any solution or workaround would be much appreciated. I’m happy to answer any questions if needed.
All the best!
Medz
The text was updated successfully, but these errors were encountered:
Источник
Floating Action Buttons
Floating action buttons (or FAB) are: “A special case of promoted actions. They are distinguished by a circled icon floating above the UI and have special motion behaviors, related to morphing, launching, and its transferring anchor point.”
For example, if we are using an email app and we are listing the inbox folder, the promoted action might be composing a new message.
The floating action button represents the primary action within a particular screen. More info and use cases of the FAB button from Google’s official design specs can be found here.
Google made available during Google I/O 2015 a support library to create floating action buttons library. In the past, third-party libraries such as makovkastar/FloatingActionButton and futuresimple/android-floating-action-button had to be used. Note that those libraries use old Support Library and you need to follow AndroidX Migration guide in order to use them in your apps.
The floating action button uses the same menu icons used for the App Bar at the top of the screen. This means the image should be single color and fit the material design guidelines. The best source for these icons is the material design icons site or the official google material icons:
Once you’ve selected the icon to use, download the image by selecting the icon and then «Icon Package» and choose the «Android» package. Note that Mac users may need to use the Unarchiver to properly unzip the icon package. Bring the various drawables into the drawable folders within your Android app.
Add this to your build.gradle file:
You should now be able to add the com.google.android.material.floatingactionbutton.FloatingActionButton view to the layout. The src attribute references the icon that should be used for the floating action.
In addition, assuming xmlns:app=»http://schemas.android.com/apk/res-auto is declared as namespace the top of your layout, you can also define a custom attribute fabSize that can reference whether the button should be normal or mini .
To place the floating action button, we will use CoordinatorLayout. A CoordinatorLayout helps facilitate interactions between views contained within it, which will be useful later to describe how to animate the button depending on scroll changes. For now we can take advantage of a feature in CoordinatorLayout that allows us to hover one element over another. We simply need to have the ListView and FloatingActionButton contained within the CoordinatorLayout and use the layout_anchor and layout_anchorGravity attributes.
The button should be placed in the bottom right corner of the screen. The recommended margin for the bottom is 16dp for phones and 24dp for tablets. In the example above, 16dp was used.
The actual drawable size should be 24dp according to the Google design specs.
When a user scrolls down a page, the floating action button should disappear. Once the page scrolls to the top, it should reappear.
To animate this part, you will need to take advantage of CoordinatorLayout, which helps choreograph animations between views defined within this layout.
Currently, you need to convert your ListViews to use RecyclerView. RecyclerView is the successor to ListView as described in this section. There is no support built-in for CoordinatorLayout to work with ListView according to this Google post. You can review this guide to help make the transition.
You must AndroidX version of RecyclerView. Other versions (such as Support Library) will not work with CoordinatorLayout. Make sure to bump your build.gradle file:
Next, you must implement a CoordinatorLayout Behavior for the Floating Action Button. This class will be used to define how the button should respond to other views contained within the same CoordinatorLayout.
Create a file called ScrollAwareFABBehavior.java that extends from FloatingActionButton.Behavior. Currently, the default behavior is used for the Floating Action Button to make room for the Snackbar as shown in this video. We want to extend this behavior to signal that we wish to handle scroll events in the vertical direction:
Because scrolling will be handled by this class, a separate method onNestedScroll() will be called. We can check the Y position and determine whether to animate in or out the button.
The final step is to associate this CoordinatorLayout Behavior to the Floating Action Button. We can define it within the XML declaration as a custom attribute app:layout_behavior :
Replace the layout file’s root element with a Coordinator Layout. This will ensure our ScrollAwareFABBehavior Class will call onNestedScroll().
Because we are defining this behavior statically within the XML, we must also implement a constructor to enable layout inflation to work correctly.
If you forget to implement this last step, you will see Could not inflate Behavior subclass error messages. See this example code for the full set of changes. Not that code uses old Support Library v4.
Note: Normally when implementing CoordinatorLayout behaviors, we need to implement layoutDependsOn() and onDependentViewChanged(), which are used to track changes in other views contained within the CoordinatorLayout. Since we only need to monitor scroll changes, we use the existing behavior defined for the Floating Action Button, which is currently implemented to track changes for Snackbars and AppBarLayout as discussed in this blog post.
A common effect is embedding the FAB near the header.
This can be achieved by use CoordinatorLayout as the root view. We need to specify layout_anchor for the FAB to the top view and layout_anchorGravity to to bottom|right|end like this:
For details check out this stackoverflow post. See the CoordinatorLayout guide for more details on that layout.
By default, the floating action button takes the color accent used for your theme. If you wish to change it, you can use the app:backgroundTint attribute:
Источник
Добавляем 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, поэтому пока что не стесняйтесь использовать это решение.
Источник
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.
Источник