Android material button ripple color

Ripple Animation

Touch feedback in material design provides an instantaneous visual confirmation at the point of contact when users interact fwith UI elements. For example, buttons now display a ripple effect when they are touched — this is the default touch feedback animation in Android 5.0. Ripple animation is implemented by the new RippleDrawable class. The ripple effect can be configured to end at the bounds of the view or extend beyond the bounds of the view. For example, the following sequence of screenshots illustrates the ripple effect in a button during touch animation:

Initial touch contact with the button occurs in the first image on the left, while the remaining sequence (from left to right) illustrates how the ripple effect spreads out to the edge of the button. When the ripple animation ends, the view returns to its original appearance. The default ripple animation takes place in a fraction of a second, but the length of the animation can be customized for longer or shorter lengths of time.

Note that the ripples will only show up on devices running Lollipop, and will fall back to a static highlight on previous versions.

In general, ripple effect for regular buttons will work by default in API 21, and for other touchable views it can be achieved by specifying

Most buttons are made with several drawables. Usually you’ll have a pressed and normal version of assets like this:

If you have a custom button with selected state, your text color changes depending on the state, etc. So the default button background is not going to work for you here. You can add this feedback for your own drawables and for custom buttons by simply wrapping them in a ripple element:

Using ?android:colorControlHighlight will give the ripple the same color as the built-in ripples in your app.

If you don’t like the default grey, you can specify what color you want android:colorControlHighlight to be in your theme.

If you want the ripple to extend past the boundary of the view, then you can instead use ?attr/selectableItemBackgroundBorderless . This works well with ImageButtons and smaller Buttons that are part of a larger View:

Источник

Ripple effect in Android

What is Ripple?

Ripple is a small wave like pattern, generally formed on the surface of some liquid when you drop something on it.

What is Ripple effect in Android?

Ripple effect provides an instantaneous visual confirmation at the point of contact when users interact with UI elements.

These UI elements could be any of the View elements.
Like – Layouts, Buttons, TextViews, ListViews, etc.

Whenever the user clicks or touches any UI element like, a button, it is desirable to provide some kind of visual confirmation, so that the user knows that their touch or click was successful. Responsive interaction encourages deeper exploration of an app by creating timely, logical, and delightful screen reactions to the user input. However, this interaction should not be distracting to the user. Traditionally in Android, this has been handled using state list drawables to provide different colored or shaded drawables which indicate that a control is in touched or pressed state. With the Android Lollipop, a new touch feedback mechanism was introduced to provide this touch feedback and is loosely based on the concept of ripples on the card metaphor which features strongly in Material design. These ripples are actually really easy to implement.

When was it introduced?

In the android development ecosystem, it was added in Android 5.0: API 21(LOLLIPOP). So, it does not work on pre-lollipop devices. However, we have external libraries which can be used to give the same effect. Links for the same are provided at the end of the blog.

Читайте также:  Все живые обои с девушками для андроида

Class hierarchy followed is :

[sourcecode language=”java”]
java.lang.Object
↳android.graphics.drawable.Drawable
↳android.graphics.drawable.LayerDrawable
↳android.graphics.drawable.RippleDrawable
[/sourcecode]

How to achieve Ripple effect?

It can be achieved in 2 ways :

(a) Programmatically – by using RippleDrawable class.
(b) By XML – by using Drawable XML that shows a ripple effect in response to state changes of the View.

In order to understand how the ripple is drawn it would be nice to slow the animation down. The ripple animation runs slower when we perform a long press, so we can use that to see exactly what’s happening.

Programmatically

Our respective class will implement View.OnTouchListener interface.
It will provide us : public abstract boolean onTouch (View v, MotionEvent event) callback.
This is called, when a touch event is dispatched to a view.

Here, v : The view, the touch event has been dispatched to.
event : The MotionEvent object containing full information about the event.
This method returns True if the listener has consumed the event, False otherwise.

The anchoring position of the ripple for a given state is specified by calling setHotspot(float, float) with the corresponding state attribute identifier.

[sourcecode language=”java”]
private RippleDrawable rippleDrawable;
private Button buttonWithRipple;

buttonWithRipple = (Button) findViewById(R.id.buttonWithRipple);
rippleDrawable = (RippleDrawable) buttonWithRipple.getBackground();
buttonWithRipple.setOnTouchListener(this);

@Override
public boolean onTouch(View v, MotionEvent event) <
switch (v.getId()) <
case R.id.buttonWithRipple :
rippleDrawable.setHotspot(event.getX(), event.getY());
rippleDrawable.setColor(ColorStateList.valueOf(getResources().getColor(R.color.red)));
break; >
return false;
>
[/sourcecode]

Here, event.getX() & event.getY() gives us current pointer coordinates. And then, we set our required color to the rippledrawable object.

By XML

Setting DEFAULT Ripple effect on Android 5.0: API 21(LOLLIPOP) devices :

  • If you want to apply the Standard ripple effect on Android 5.0: API 21 or more, which should be limited to your view (bounded ripple), just apply to your View background :

[sourcecode language=”java”]
android:background=»?android:attr/selectableItemBackground»
[/sourcecode]

This background attribute value :

will provide default ripple effect, which will constrain the animation, within the View that’s handling the touch event.

  • If you want to apply the standard ripple effect on Android 5.0: API 21 or more, which should not be limited to your view (unbounded ripple), just apply to your View background :

[sourcecode language=”java”]
android:background=»?android:attr/selectableItemBackgroundBorderless»[/sourcecode]

This background attribute value :

[sourcecode language=”java”] selectableItemBackgroundBorderless[/sourcecode]

will provide default ripple effect, which will extend the animation beyond the bounds of its View that’s handling the touch event. It will be bounded by the nearest parent of the view with a non-null background.

Standard bounded Ripple Effect Standard Unbounded Ripple Effect

Setting CUSTOMISED Ripple effect on Android 5.0: API 21(LOLLIPOP) devices :

We create a touch feedback drawable that shows a ripple effect in response to state changes, using the ripple as root element.

This drawable may contain 0 or more child layers, including a special mask layer that is not drawn to the screen.

Attributes are as under :

  • android:color – the color to use for ripple effects.

1. Must be a color value, in the form of “#rgb”, “#argb”, “#rrggbb”, or “#aarrggbb”.
2. This may also be a reference to a resource (in the form “@[package:]type:name”) or theme attribute (in the form “?[package:][type:]name”) containing a value of this type. This corresponds to the global attribute resource symbol color.

  • android:radius – radius of the ripple when fully expanded.

1. Default value is computed based on the size of the ripple’s container.
2. Must be a dimension value, which is a floating point number appended with a unit (like : px, dp, sp, in, mm).
3. This may also be a reference to a resource (in the form “@[package:]type:name”) or theme attribute (in the form “?[package:] [type:]name”) containing a value of this type. This corresponds to the global attribute resource symbol radius.

USAGE :

Set this drawable as the background to your view :

  • Drawable with only a mask layer and no child layer

If a mask layer is set and the ripple is set as a View background, the ripple effect will be masked against that layer.

  • Drawable with a child layer and a mask layer

If a mask layer is set and the ripple is set as a View background, the ripple effect will be masked against that layer before it is drawn over the composite of the remaining child layers (if they exist).
Here, background color of button is changed by setting the child layer in the Ripple drawable XML.

  • Drawable with no mask layer or child layer
Читайте также:  Acer w700 установка андроид

If no child or mask layer is specified and the ripple is set as a View background, the ripple will be drawn atop the first available parent background within the View’s hierarchy.

Drawable with only a mask Drawable with a mask Drawable with no mask or

layer and no child layer layer and a child layer child layer

Below are the references to various libraries which can be used to apply Ripple Effect on Pre-Lollipop devices :

  • https://github.com/siriscac/RippleView.git
  • https://github.com/balysv/material-ripple.git
  • https://github.com/traex/RippleEffect.git
  • https://android-arsenal.com/tag/167

Thanks to Google for its Material Design 🙂

Источник

Hands-on with Material Components for Android: Buttons

Part 4 of a series covering practical usage of Material Components for Android

This post will be covering the features and API of Button components. To find out how to handle initial setup of Material Components for Android (including the Gradle dependency and creating an app theme), please see my original post:

Setting up a Material Components theme for Android

Attribute by attribute

Buttons are arguably the most widely-used components in any app. This is largely due to their versatility, allowing users to perform actions and make choices that ultimately guide the flow of an experience. A single line of contained text and/or an icon indicate the action a button can perform.

Material Buttons are slightly different to traditional Android buttons in that they do not include additional insets (4dp on the left/right) and have more letter-spacing, different default colors and other attributes that improve legibility and affordance amongst other components.

From a design perspective, there are three main types of buttons which are intended to offer hierarchical levels of emphasis:

  • Text button (low emphasis): No container. Best used for less important actions, especially when other main content needs to be emphasised.

In addition to this, buttons can be grouped together into a fourth type: Toggle button. This allows related button actions to be horizontally arranged in a common container. The buttons themselves can be selected/deselected to indicate an active/inactive choice.

Basic usage 🏁

A MaterialButton can be included in your layout like so:

Choosing a style 🤔

As discussed in the intro section above, a variety of button types exist. These types map to styles that you can apply to a MaterialButton . There also exists a variety of sub-styles for specific use cases, such as to adjust padding for an icon. The full list of styles and their attributes can be found on GitHub. These style variants inherit from Widget.MaterialComponents.Button , each with an optional style suffix:

  • Text button: *.TextButton (main), *.TextButton.Icon , *.TextButton.Snackbar , *.TextButton.Dialog , *.TextButton.Dialog.Icon , *.TextButton.Dialog.Flush
  • Outlined button: *.OutlinedButton (main), *.OutlinedButton.Icon
  • Contained button (unelevated): *.UnelevatedButton (main), *.UnelevatedButton.Icon
  • Contained button (raised): No suffix (default, main), *.Icon

Adding an icon 🔷

An icon can be added to a button. It is displayed at the start, before the text label. In order to get the correct icon padding, it is recommended that you use a *.Icon style variant (shown above in the “Choosing a style” section).

The icon can be added in XML:

Alternatively, it can be done programmatically:

A few additional attributes exist for adjusting the icon size and position:

  • iconSize : The width/height of the icon. The default value is the supplied Drawable ’s intrinsic width.

  • iconGravity : The gravity of the icon. This can be set to start ( ICON_GRAVITY_START , default, at start of button), end ( ICON_GRAVITY_END , at end of button), textStart ( ICON_GRAVITY_TEXT_START , at start of centered text label) or textEnd ( ICON_GRAVITY_TEXT_END , at end of centered text label).

  • iconPadding : The spacing between the icon and the text label. Typically you would not want to change this. The default value is 4dp for text buttons and 8dp for all other types.

Attributes related to icon tinting are discussed in the “Theming” section below.

Grouping Buttons to create a Toggle Button 👨‍👩‍👧‍👦

In order to create a toggle button, we need to add MaterialButton s as child View s to a MaterialButtonToggleGroup (a custom ViewGroup ).

Note: MaterialButtonToggleGroup was added in the 1.1.0-alpha05 release of Material Components for Android.

Grouping

This can be done in XML:

Alternatively, it can be done programmatically:

The MaterialButtonToggleGroup handles layout and adjusting of only the relevant shape corners in the row of MaterialButton s. The appearance of the MaterialButton s is determined by whichever style they each use. It is advised to use a consistent style for all children and also recommended to use the outlined button type.

Читайте также:  Чем открыть пдф файл андроид

Adjusting selected behavior

When added to a MaterialButtonToggleGroup , child MaterialButton s automatically become “selectable” (i.e. The android:checkable attribute is set to true).

Thus, there exists a couple of attributes for adjusting how MaterialButtonToggleGroup manages this:

  • singleSelection : Determines whether or not only a single button in the group can be checked at a time. The default value is false, meaning multiple buttons can be checked/unchecked independently.

Listening for selection state

We are able to query for and adjust the current checked button(s) in a variety of ways:

We are also able to listen for checked changes by adding an OnButtonCheckedListener to a MaterialButtonToggleGroup :

Listeners can also be removed with the MaterialButtonToggleGroup#removeListener and MaterialButtonToggleGroup#clearListeners functions.

Orientation

The default arrangement of buttons within a toggle group is horizontal. However, seeing as MaterialButtonToggleGroup extends LinearLayout , it also supports vertical arrangement. This can be set programmatically or in XML:

The interesting thing to note here is the extra attributes on the child MaterialButton (s). It is recommended to set the width to match_parent and to remove the top/bottom insets from the child buttons so as to have them sit flush against each other vertically. This also, however, requires adjusting the minHeight to make up for the lack of insets.

Theming 🎨

Buttons can be themed in terms of the three Material Theming subsystems: color, typography and shape. We have already shown which styles to use in the “Choosing a style” section above. When implementing a global custom MaterialButton and MaterialButtonToggleGroup styles, reference them in your app theme with the materialButtonStyle / materialButtonOutlinedStyle and materialButtonToggleGroupStyle attributes respectively.

Color

The color of the MaterialButton background can be customized with the backgroundTint attribute. This requires a ColorStateList , meaning a for checked/enabled/disabled states is required. It defaults to colorPrimary (enabled)/ colorOnSurface (disabled) for contained buttons and transparent(unchecked)/ colorPrimary (checked) for all other types, with different opacities per state. There is also a backgroundTintMode attribute to change the tint PorterDuff.Mode , although typically you would want to keep this the same.

The color of the text label can be customized with the android:textColor attribute. This too requires a ColorStateList . It defaults to colorOnPrimary (enabled)/ colorOnSurface (disabled) for contained buttons and colorPrimary (enabled or checked)/ colorOnSurface (disabled or unchecked) for all other types, with different opacities per state.

The color of the optional icon can be customized with the iconTint attribute. This too requires a ColorStateList and the defaults are the same as those of android:textColor . As before, there is also an iconTintMode attribute.

Lastly, the color of the button touch ripple can be customized with the rippleColor attribute. It too accepts a ColorStateList and defaults to colorOnPrimary for contained buttons and colorPrimary for all other types, with different opacities per state.

Typography

The button text label will adopt the fontFamily attribute defined in your app theme.

While you would typically want to keep most aspects of the button text appearance as is, the Material Guidelines suggest we can use sentence case over the standard all caps for the text label, if desired. To achieve this, we would create a new style:

We could apply this directly to a button or in an individual button style by referencing it with the android:textAppearance attribute. Alternatively, it can be applied globally by referencing it in your app theme with the textAppearanceButton attribute.

Shape

The shape of a button background can be customized with the shapeAppearance attribute. This defaults to shapeAppearanceSmallComponent .

While not strictly shape theming, it is worth mentioning that the width of an outlined button stroke can be adjusted with the strokeWidth attribute. This defaults to 1dp.

More resources 📚

  • The source code for the Playground app used in this article can be found on GitHub.
  • Buttons Design Documentation
  • Buttons API Documentation
  • Toggle Buttons API Documentation

I hope this post has provided some insight into Material Buttons and how they can be used in your Android app(s). If you have any questions, thoughts or suggestions then I’d love to hear from you!

Источник

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