- 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
- Android fab icon color
- About
- Android меняет цвет кнопки плавающего действия
- 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:
Источник
Android fab icon color
Floating Action Button with Speed-Dial Menu
This library provides a clickable floating action button (FAB) with an optional speed-dial menu. The FAB can trigger a standard click listener or a open the speed-dial menu with further options. All aspects of the FAB and speed-dial menu are customisable.
You can try the demo in one of two ways:
Clone this repository and install the demo app from the app/ folder (you can do this with Gradle, using gradle clean installDebug ).
Download the sample app from the Google Play Store: Floating Action Button Demo.
Note: depending on your app’s configuration, you may need to add the following to your ProGuard rules:
Note: all of the instructions below assume that the FAB is referenced by the variable fab , i.e.
Placing the FAB in Your Layout
The FloatingActionButton view must be placed at the root of your layout, above all other views, and with maximum width and height. This allows the semi-transparent layer to expand and cover the entire layout when the speed-dial menu is opened.
The FAB can be positioned in any of the four corners of the activity via XML or with fab.setButtonPosition(. ) . The default position is the bottom-end corner.
The FAB is aware of text-direction (right-to-left or left-to-right) and adjusts the meaning of «start» and «end» positions accordingly. This functionality can be overridden using the named constants for left and right.
The FAB can be offset from any of the four edges to precisely control its location, although this is not needed in most applications. The offset can be added to the top, bottom, start, end, left or right of the view. Where left and/or right offsets are specified they will both take precedence over start/end offsets.
Note: any offset is applied in addition to the default spacing around the FAB. If you need to counter this, subtract the default spacing ( fab.getOriginalInternalOffset() in Java or fab.originalInternalOffset in Kotlin) from the value you want to use.
The icon displayed in the centre of the FAB can be set via XML using a Drawable reference or with fab.setButtonIconResource(. ) using a Drawable resource ID. The icon will be centred in a 24dp x 24dp view group, as per the Android Material Design specs.
FAB Background Colour
The background colour of the FAB can be set via XML using a colour reference or programmatically with fab.setButtonBackgroundColour(. ) using an aRGB colour value (e.g. 0xffff9900 for dark orange). Note that the second method does not take a colour resource ID, so passing in R.color.some_colour_name will not work.
FAB Click Listener
A click listener can be added to the FAB in the same way as any other button. The view passed to the listener can be safely cast to a FloatingActionButton .
The speed-dial menu is enabled by creating a class that extends SpeedDialMenuAdapter and passing it to fab.setSpeedDialMenuAdapter(. ) . The adapter class methods are documented in-situ.
Speed-Dial Menu Content Cover
The content cover expands from the FAB when the speed-dial menu is opened to obscure the rest of the app content and emphasise the menu. It also prevents controls in the rest of the app from being clicked on while the speed-dial menu is open; tapping outside the menu while it is open and the cover is displayed will cause the menu to close.
The colour of the content cover can be set programmatically with fab.setContentCoverColour(. ) using an aRGB colour value (e.g. 0x99ff9900 for a semi-transparent dark orange). Note that this method does not take a colour resource ID, so passing in R.color.some_colour_name will not work.
The cover can be enabled/disabled programmatically with fab.setContentCoverEnabled(. ) .
Speed-Dial Menu State Change Listeners
State change events are fired when the speed-dial menu opens or closes, which can be received with fab.setOnSpeedDialMenuOpenListener(. ) and fab.setOnSpeedDialMenuCloseListener(. ) .
The FAB can be hidden and shown with the fab.hide() and fab.show() methods, and the method fab.isShown() will return a boolean indicating the current state. These methods animate the FAB in and out of visibility and set the entire view container’s visibility to GONE . If the speed-dial menu is open when .hide() is called it will be closed.
If the FAB is hidden in the XML layout (i.e. with android:visibility=»gone» ) when initialise the FAB will start in the correct hidden state and can still be shown/hidden with the fab.hide() and fab.show() methods.
The speed-dial menu can be manually opened and closed with fab.openSpeedDialMenu() and fab.closeSpeedDialMenu() . These methods will do nothing if no speed-dial menu adapter is set, if an adapter is set but disabled, if the FAB is hidden, or if they are called when the menu is already in the indicated state (i.e. fab.openSpeedDialMenu() will do nothing if the menu is already open).
Access to Underlying Views
The FAB’s key underlying views can be accessed using the three properties/methods detailed below:
The card view is implemented as a CardView on SDK 21+ and a LinearLayout on SDK 20 and below.
The content cover view and icon wrapper are implemented as a View and LinearLayout respectively on all SDKs.
Note: Known Compatibility Issues
In Android 4.x there is an issue with Vector Drawable icons. If you want to use Vector Drawables as icons (e.g app:buttonIcon=»@drawable/ic_add» ) you will need to add the following snippet in your Activity classes.
Note: Click Action Priority
As per Material Design specs, the FAB functions as a regular button or a trigger for the speed-dial menu, but not both. For this reason, the click listener and the speed-dial menu are never invoked at the same time.
The speed-dial menu is given priority: when the FAB is clicked the speed-dial menu will be shown if the speed-dial menu adapter is non-null, the adapter’s isEnabled() function returns true and the adapter’s getCount() returns a number greater than zero. Otherwise, the FAB’s click listener will be called (if it has been set).
Setting a speed-dial menu adapter does not remove the click listener, and setting a click listener does not remove the speed-dial menu adapter. For an example of how the two operation modes interact, check the demo app’s source code.
To receive state change updates when the speed-dial menu is opened or closed, use the open/close listeners described above.
Note: State Preservation
The following properties are preserved when a configuration change (like a screen orientation change) happens:
- FAB hidden/shown
- FAB position
- FAB background colour
- FAB icon
- Speed-dial menu content cover colour
- Speed-dial menu content cover enabled/disabled
The following properties are not preserved and will need to be restored by the parent activity/fragment:
- FAB click listener
- Speed-dial menu adapter
- Speed-dial menu open/close listeners
About
Floating action button (FAB) for Android with speed-dial menu functionality
Источник
Android меняет цвет кнопки плавающего действия
Я пытался изменить цвет кнопки плавающего действия материала, но безуспешно.
Я попытался добавить:
Но ничего из вышеперечисленного не сработало. Я также попробовал решения в предложенном дублирующем вопросе, но ни один из них не работает; кнопка оставалась зеленой и также стала квадратной.
PS Было бы также неплохо узнать, как добавить волновой эффект, но и этого не мог понять.
Как описано в документации , по умолчанию он принимает цвет, заданный в атрибуте styles.xml colorAccent .
Цвет фона этого представления по умолчанию соответствует цвету акцента вашей темы. Если вы хотите изменить это во время выполнения, вы можете сделать это через setBackgroundTintList (ColorStateList).
Если вы хотите изменить цвет
- в XML с атрибутом приложения: backgroundTint
- в коде с .setBackgroundTintList (ответ ниже ywwynm )
Как упоминалось в комментариях @Dantalian, если вы хотите изменить цвет значка для библиотеки поддержки проектирования до версии 22 (включительно) , вы можете использовать
Для библиотеки поддержки проектирования начиная с версии v23 вы можете использовать:
Также с androidX библиотеками вам нужно установить границу 0dp в макете xml:
Ответ Виджета Бадиганнавара правильный, но, ColorStateList как правило, он сложный, и он не сказал нам, как это сделать. Поскольку мы часто фокусируемся на изменении View цвета в нормальном и нажатом состоянии, я собираюсь добавить больше деталей:
Если вы хотите изменить FAB цвет в нормальном состоянии, вы можете просто написать
Если вы хотите изменить FAB цвет в нажатом состоянии, спасибо за Библиотеку поддержки дизайна 22.2.1 , вы можете просто написать
При установке этого атрибута, когда вы долго нажимаете на кнопку FAB , пульсация с вашим цветом появится в точке касания и раскроется на всю поверхность FAB . Пожалуйста, обратите внимание, что это не изменит FAB цвет в нормальном состоянии. Ниже API 21 (Lollipop) эффект ряби отсутствует, но FAB его цвет все равно будет меняться при нажатии.
Наконец, если вы хотите реализовать более сложный эффект для состояний, то вам нужно углубиться в этот вопрос ColorStateList , вот такой вопрос, обсуждающий его: Как мне создать ColorStateList программно? ,
ОБНОВЛЕНИЕ: Спасибо за комментарий @ Кейтлин. Чтобы удалить обводку FAB, используя backgroundTint в качестве цвета, вы можете установить app:borderWidth=»0dp» в xml.
Источник
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.
Источник