Android fab button color

Android изменение цвета кнопки плавающего действия

часами пытался изменить цвет кнопки плавающего действия материала, но безуспешно.

Я пытался добавить

но ничего из вышеперечисленного не сработало. Я также пробовал решения в «дублировать вопрос», но ни один из них не работает, кнопка осталась зеленой и также стала квадратной.

Я хотел бы получить подробный ответ, спасибо.

П. С. было бы неплохо также знать, как добавить эффект пульсации, не могла понять что либо.

18 ответов

как описано в документация по умолчанию он принимает цвет в стили.в XML атрибут colorAccent.

цвет фона этого представления по умолчанию соответствует colorAccent вашей темы. Если вы хотите изменить это во время выполнения, вы можете сделать это через setBackgroundTintList(ColorStateList).

Если вы хотите изменить цвет

  • в XML с атрибутом app:backgroundTint
  • в коде .setBackgroundTintList (ответ ниже ywwynm)

Как @Dantalian писал в комментариях, если вы хотите изменить цвет, вы можете использовать

Vijet Badigannavar ответ правильный, но с помощью ColorStateList обычно сложнее и он не сказал нам, как это делать. Так как мы часто фокусируемся на изменении View цвет в нормальном и нажатом состоянии, я собираюсь добавить более подробную информацию:

если вы хотите изменить FAB цвет в нормальном состоянии, вы можете просто написать

если вы хотите изменить FAB цвет в отжатом положении, спасибо для библиотеки поддержки дизайна 22.2.1, вы можете просто написать

установив этот атрибут, при длительном нажатии кнопки FAB , рябь с вашим цветом появится в вашей точке касания и раскроется на всю поверхность FAB . Пожалуйста, обратите внимание, что это не изменит FAB цвет в нормальном состоянии. Ниже API 21 (Lollipop) нет эффекта пульсации, но FAB ‘S цвет будет по-прежнему меняться, когда вы нажимаете его.

наконец, если вы хотите реализовать более сложный эффект для состояний, то вы должны глубоко копать в ColorStateList , вот так вопрос обсуждаем: как создать ColorStateList программно?.

обновление: Спасибо за комментарий @Kaitlyn. Чтобы удалить ход FAB, используя backgroundTint в качестве цвета, вы можете установить app:borderWidth=»0dp» в вашем xml.

As Василь Валча отметил в комментарии это проще, чем кажется, но есть тонкая разница, которую я не замечал в своем XML.

обратите внимание, что это:

и не

Если вы пытаетесь изменить цвет FAB с помощью приложения, есть некоторые проблемы. рамка кнопки имеет разный цвет, так что вы должны сделать:

Источник

Изменение цвета плавающей кнопки Android

Старался часами менять цвет кнопки Material Floating Action, но безуспешно.

Я попытался добавить

Но ничего из этого не было. Я также пробовал решения в «дублированном вопросе» , но никто из них не работает, кнопка оставалась зеленой, а также стала квадратом.

Я хотел бы получить подробный ответ, спасибо.

PS Было бы также хорошо знать, как добавить эффект пульсации, и не мог этого понять.

Как описано в документации , по умолчанию он принимает цвет, установленный в атрибуте styles.xml colorAccent .

Цвет фона этого представления по умолчанию соответствует цвету вашей темы. Если вы хотите изменить это во время выполнения, вы можете сделать это через setBackgroundTintList (ColorStateList).

Если вы хотите изменить цвет

  • В XML с приложением атрибута : backgroundTint
  • В коде с .setBackgroundTintList (ответ ниже по ywwynm )

Как отметил @Dantalian в комментариях, если вы хотите изменить цвет значка, вы можете использовать

Ответ Vijet Badigannavar правильный, но использование ColorStateList обычно затруднено, и он не рассказал нам, как это сделать. Поскольку мы часто фокусируемся на изменении цвета View в нормальном и нажатом состоянии, я собираюсь добавить дополнительные сведения:

Читайте также:  Виртуальные обои для андроид

Если вы хотите изменить цвет FAB в нормальном состоянии, вы можете просто написать

Если вы хотите изменить цвет FAB в нажатом состоянии, спасибо Библиотеке поддержки дизайна 22.2.1 , вы можете просто написать

Установив этот атрибут, когда вы долго нажимаете FAB , рябь с вашим цветом появится в вашей точке касания и откроется на всю поверхность FAB . Обратите внимание, что он не изменит цвет FAB в нормальном состоянии. Ниже API 21 (Lollipop) эффект пульсации отсутствует, но цвет FAB будет по-прежнему изменяться, когда вы нажимаете его.

Наконец, если вы хотите реализовать более сложный эффект для состояний, тогда вы должны глубоко ColorStateList в ColorStateList , вот вопрос SO, обсуждающий его: Как я могу создать ColorStateList программным путем? ,

ОБНОВЛЕНИЕ: Спасибо за комментарий @ Kaitlyn. Чтобы удалить ход FAB с использованием backgroundTint в качестве его цвета, вы можете установить app:borderWidth=»0dp» в свой xml.

Как отметил в комментарии Василий Вълчев, это проще, чем кажется, но есть тонкая разница, которую я не замечал в своем XML.

И не

Если вы пытаетесь изменить цвет FAB с помощью приложения, есть какая-то проблема. Кадр кнопки имеет разный цвет, так что вы должны сделать:

И в коде установите цвет:

FAB окрашен в соответствии с вашим colorAccent .

Документ предполагает, что по умолчанию он принимает цвет @ / акцент. Но мы можем переопределить его по коду, используя

Минимальная версия API для использования этой библиотеки – 15, поэтому вам необходимо ее обновить! Если вы не хотите это делать, вам нужно определить пользовательскую возможность рисования и украсить ее!

Другие решения могут работать. Это подход 10-фунтовых горилл, который имеет то преимущество, что он широко применим в этом и подобных случаях:

Обратите внимание, что вы добавляете цвета в res / values ​​/ color.xml и включаете атрибут в свой fab

Благодаря автозаполнению. Мне повезло после нескольких ударов и испытаний:

– или – (оба в основном одно и то же)

Это работало для меня в версии API 17 с библиотекой дизайна 23.1.0.

У меня такая же проблема, и все это хватало моих волос. Спасибо за это https://stackoverflow.com/a/35697105/5228412

Что мы можем сделать..

Он отлично работает для меня и желает других, которые доберутся сюда.

То, что нам не хватает, заключается в том, что перед установкой цвета на кнопке важно работать с тем значением, которое вы хотите для этого цвета. Таким образом, вы можете перейти к значениям> цвет. Вы найдете по умолчанию, но вы также можете создавать цвета, обходя и вставляя их, меняя цвета и имена. Затем … когда вы идете изменить цвет плавающей кнопки (в activity_main), вы можете выбрать тот, который вы создали

Exemple – код на значениях> цвета с цветами по умолчанию + еще 3 цвета, которые я создал:

Теперь моя плавающая кнопка действия с цветом, который я создал и назвал «corPar»:

Это сработало для меня. Удачи!

Если вы используете Xamarin для разработки приложений для Android, используйте ниже код для изменения цвета плавающей кнопки.

«# 000000» используется для черного цвета, который вы можете изменить в соответствии с вашими требованиями.

Источник

Android fab button 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.

Читайте также:  Android icon on instagram

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

Источник

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