Skip to content

Commit

Permalink
[Checkbox] Added support for error state.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 453496914
  • Loading branch information
leticiarossi authored and pekingme committed Jun 8, 2022
1 parent 5c0003c commit 8dd9c7e
Show file tree
Hide file tree
Showing 10 changed files with 320 additions and 17 deletions.
44 changes: 39 additions & 5 deletions docs/components/Checkbox.md
Expand Up @@ -35,6 +35,13 @@ Material Components for Android library. For more information, go to the
[Getting started](https://github.com/material-components/material-components-android/tree/master/docs/getting-started.md)
page.

```xml
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/label"/>
```

**Note:** `<CheckBox>` is auto-inflated as
`<com.google.android.material.button.MaterialCheckBox>` via
`MaterialComponentsViewInflater` when using a `Theme.Material3.*`
Expand All @@ -47,6 +54,33 @@ screen readers, such as TalkBack. Text rendered in check boxes is automatically
provided to accessibility services. Additional content labels are usually
unnecessary.

### Setting the error state on checkbox

In the layout:

```xml
<CheckBox
...
app:errorShown="true"/>
```

In code:

```kt
// Set error.
checkbox.errorShown = true

// Optional listener:
checkbox.addOnErrorChangedListener { checkBox, errorShown ->
// Responds to when the checkbox enters/leaves error state
}
}

// To set a custom accessibility label:
checkbox.errorAccessibilityLabel = "Error: custom error announcement."

```

## Checkbox

A checkbox is a square button with a check to denote its current state.
Expand Down Expand Up @@ -75,24 +109,24 @@ In the layout:
```xml
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/label_1"/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="wrap_content"
android:text="@string/label_2"/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="wrap_content"
android:text="@string/label_3"/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="wrap_content"
android:text="@string/label_4"/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="@string/label_5"/>
```
Expand Down
165 changes: 155 additions & 10 deletions lib/java/com/google/android/material/checkbox/MaterialCheckBox.java
Expand Up @@ -29,13 +29,17 @@
import androidx.appcompat.widget.AppCompatCheckBox;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityNodeInfo;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.widget.CompoundButtonCompat;
import com.google.android.material.color.MaterialColors;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ViewUtils;
import com.google.android.material.resources.MaterialResources;
import java.util.LinkedHashSet;

/**
* A class that creates a Material Themed CheckBox.
Expand All @@ -49,16 +53,36 @@ public class MaterialCheckBox extends AppCompatCheckBox {

private static final int DEF_STYLE_RES =
R.style.Widget_MaterialComponents_CompoundButton_CheckBox;
private static final int[][] ENABLED_CHECKED_STATES =
private static final int[] ERROR_STATE_SET = {R.attr.state_error};
private static final int[][] CHECKBOX_STATES =
new int[][] {
new int[] {android.R.attr.state_enabled, android.R.attr.state_checked}, // [0]
new int[] {android.R.attr.state_enabled, -android.R.attr.state_checked}, // [1]
new int[] {-android.R.attr.state_enabled, android.R.attr.state_checked}, // [2]
new int[] {-android.R.attr.state_enabled, -android.R.attr.state_checked} // [3]
new int[] {android.R.attr.state_enabled, R.attr.state_error}, // [0]
new int[] {android.R.attr.state_enabled, android.R.attr.state_checked}, // [1]
new int[] {android.R.attr.state_enabled, -android.R.attr.state_checked}, // [2]
new int[] {-android.R.attr.state_enabled, android.R.attr.state_checked}, // [3]
new int[] {-android.R.attr.state_enabled, -android.R.attr.state_checked} // [4]
};
@NonNull private final LinkedHashSet<OnErrorChangedListener> onErrorChangedListeners =
new LinkedHashSet<>();
@Nullable private ColorStateList materialThemeColorsTintList;
private boolean useMaterialThemeColors;
private boolean centerIfNoTextEnabled;
private boolean errorShown;
private CharSequence errorAccessibilityLabel;

/**
* Callback interface invoked when the checkbox error state changes.
*/
public interface OnErrorChangedListener {

/**
* Called when the error state of a checkbox changes.
*
* @param checkBox the {@link MaterialCheckBox}
* @param errorShown whether the checkbox is on error
*/
void onErrorChanged(@NonNull MaterialCheckBox checkBox, boolean errorShown);
}

public MaterialCheckBox(Context context) {
this(context, null);
Expand Down Expand Up @@ -90,6 +114,9 @@ public MaterialCheckBox(Context context, @Nullable AttributeSet attrs, int defSt
attributes.getBoolean(R.styleable.MaterialCheckBox_useMaterialThemeColors, false);
centerIfNoTextEnabled =
attributes.getBoolean(R.styleable.MaterialCheckBox_centerIfNoTextEnabled, true);
errorShown = attributes.getBoolean(R.styleable.MaterialCheckBox_errorShown, false);
errorAccessibilityLabel =
attributes.getText(R.styleable.MaterialCheckBox_errorAccessibilityLabel);

attributes.recycle();
}
Expand Down Expand Up @@ -130,6 +157,121 @@ protected void onAttachedToWindow() {
}
}

@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableStates = super.onCreateDrawableState(extraSpace + 1);

if (isErrorShown()) {
mergeDrawableStates(drawableStates, ERROR_STATE_SET);
}

return drawableStates;
}

@Override
public void onInitializeAccessibilityNodeInfo(@Nullable AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
if (info == null) {
return;
}

if (isErrorShown()) {
info.setText(info.getText() + ", " + errorAccessibilityLabel);
}
}

/**
* Sets whether the checkbox should be on error state. If true, the error color will be applied to
* the checkbox.
*
* @param errorShown whether the checkbox should be on error state.
* @see #isErrorShown()
* @attr ref com.google.android.material.R.styleable#MaterialCheckBox_errorShown
*/
public void setErrorShown(boolean errorShown) {
if (this.errorShown == errorShown) {
return;
}
this.errorShown = errorShown;
refreshDrawableState();
for (OnErrorChangedListener listener : onErrorChangedListeners) {
listener.onErrorChanged(this, this.errorShown);
}
}

/**
* Returns whether the checkbox is on error state.
*
* @see #setErrorShown(boolean)
* @attr ref com.google.android.material.R.styleable#MaterialCheckBox_errorShown
*/
public boolean isErrorShown() {
return errorShown;
}

/**
* Sets the accessibility label to be used for the error state announcement by screen readers.
*
* @param resId resource ID of the error announcement text
* @see #setErrorShown(boolean)
* @see #getErrorAccessibilityLabel()
* @attr ref com.google.android.material.R.styleable#MaterialCheckBox_errorAccessibilityLabel
*/
public void setErrorAccessibilityLabelResource(@StringRes int resId) {
setErrorAccessibilityLabel(resId != 0 ? getResources().getText(resId) : null);
}

/**
* Sets the accessibility label to be used for the error state announcement by screen readers.
*
* @param errorAccessibilityLabel the error announcement
* @see #setErrorShown(boolean)
* @see #getErrorAccessibilityLabel()
* @attr ref com.google.android.material.R.styleable#MaterialCheckBox_errorAccessibilityLabel
*/
public void setErrorAccessibilityLabel(@Nullable CharSequence errorAccessibilityLabel) {
this.errorAccessibilityLabel = errorAccessibilityLabel;
}

/**
* Returns the accessibility label used for the error state announcement.
*
* @see #setErrorAccessibilityLabel(CharSequence)
* @attr ref com.google.android.material.R.styleable#MaterialCheckBox_errorAccessibilityLabel
*/
@Nullable
public CharSequence getErrorAccessibilityLabel() {
return errorAccessibilityLabel;
}

/**
* Adds a {@link OnErrorChangedListener} that will be invoked when the checkbox error state
* changes.
*
* <p>Components that add a listener should take care to remove it when finished via {@link
* #removeOnErrorChangedListener(OnErrorChangedListener)}.
*
* @param listener listener to add
*/
public void addOnErrorChangedListener(@NonNull OnErrorChangedListener listener) {
onErrorChangedListeners.add(listener);
}

/**
* Remove a listener that was previously added via {@link
* #addOnErrorChangedListener(OnErrorChangedListener)}
*
* @param listener listener to remove
*/
public void removeOnErrorChangedListener(@NonNull OnErrorChangedListener listener) {
onErrorChangedListeners.remove(listener);
}

/** Remove all previously added {@link OnErrorChangedListener}s. */
public void clearOnErrorChangedListeners() {
onErrorChangedListeners.clear();
}

/**
* Forces the {@link MaterialCheckBox} to use colors from a Material Theme. Overrides any
* specified ButtonTintList. If set to false, sets the tints to null. Use {@link
Expand Down Expand Up @@ -167,21 +309,24 @@ public boolean isCenterIfNoTextEnabled() {

private ColorStateList getMaterialThemeColorsTintList() {
if (materialThemeColorsTintList == null) {
int[] checkBoxColorsList = new int[ENABLED_CHECKED_STATES.length];
int[] checkBoxColorsList = new int[CHECKBOX_STATES.length];
int colorControlActivated = MaterialColors.getColor(this, R.attr.colorControlActivated);
int colorError = MaterialColors.getColor(this, R.attr.colorError);
int colorSurface = MaterialColors.getColor(this, R.attr.colorSurface);
int colorOnSurface = MaterialColors.getColor(this, R.attr.colorOnSurface);

checkBoxColorsList[0] =
MaterialColors.layer(colorSurface, colorControlActivated, MaterialColors.ALPHA_FULL);
MaterialColors.layer(colorSurface, colorError, MaterialColors.ALPHA_FULL);
checkBoxColorsList[1] =
MaterialColors.layer(colorSurface, colorOnSurface, MaterialColors.ALPHA_MEDIUM);
MaterialColors.layer(colorSurface, colorControlActivated, MaterialColors.ALPHA_FULL);
checkBoxColorsList[2] =
MaterialColors.layer(colorSurface, colorOnSurface, MaterialColors.ALPHA_DISABLED);
MaterialColors.layer(colorSurface, colorOnSurface, MaterialColors.ALPHA_MEDIUM);
checkBoxColorsList[3] =
MaterialColors.layer(colorSurface, colorOnSurface, MaterialColors.ALPHA_DISABLED);
checkBoxColorsList[4] =
MaterialColors.layer(colorSurface, colorOnSurface, MaterialColors.ALPHA_DISABLED);

materialThemeColorsTintList = new ColorStateList(ENABLED_CHECKED_STATES, checkBoxColorsList);
materialThemeColorsTintList = new ColorStateList(CHECKBOX_STATES, checkBoxColorsList);
}
return materialThemeColorsTintList;
}
Expand Down
Expand Up @@ -20,4 +20,7 @@
<public name="Widget.Material3.CompoundButton.CheckBox" type="style"/>

<public name="centerIfNoTextEnabled" type="attr"/>
<public name="errorShown" type="attr"/>
<public name="errorAccessibilityLabel" type="attr"/>
<public name="state_error" type="attr"/>
</resources>
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2022 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- Disabled -->
<item android:alpha="@dimen/material_emphasis_disabled" android:color="?attr/colorOnSurface" android:state_enabled="false"/>

<!-- Error -->
<item android:color="?attr/colorError" app:state_error="true"/>

<!-- Checked -->
<item android:color="?attr/colorPrimary" android:state_checked="true"/>

<!-- Unchecked -->
<item android:color="?attr/colorOnSurface" android:state_checked="false"/>
</selector>
13 changes: 13 additions & 0 deletions lib/java/com/google/android/material/checkbox/res/values/attrs.xml
Expand Up @@ -26,5 +26,18 @@
<!-- Whether the MaterialCheckBox button drawable (checkbox icon) will be
centered when there is no text set for the checkbox. Default is true. -->
<attr name="centerIfNoTextEnabled" format="boolean"/>
<!-- Whether the checkbox should be in the error state. If true, it'll be
tinted with the error color. -->
<attr name="errorShown" format="boolean"/>
<!-- The error accessibility label that is announced by screen readers when
the checkbox is in the error state. -->
<attr name="errorAccessibilityLabel" format="string"/>
</declare-styleable>

<declare-styleable name="MaterialCheckBoxStates">
<!-- Error state of the checkbox. Behaves as part of existing states; a
checkbox is always one of checked/unchecked and can also be on error or
not. -->
<attr name="state_error" format="boolean"/>
</declare-styleable>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2022 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<resources>
<!-- Following the "Error: <error message>" pattern of the edit text. -->
<string name="error_a11y_label" description="Screen reader announcement for when a checkbox is on error. [CHAR LIMIT=NONE]">
Error: invalid
</string>
</resources>
Expand Up @@ -26,7 +26,8 @@
<style name="Base.Widget.Material3.CompoundButton.CheckBox" parent="Widget.MaterialComponents.CompoundButton.CheckBox">
<!-- Inherit default text color since the component doesn't draw a surface. -->
<item name="android:textAppearance">?attr/textAppearanceBodyMedium</item>
<item name="buttonTint">@color/m3_selection_control_button_tint</item>
<item name="buttonTint">@color/m3_checkbox_button_tint</item>
<item name="errorAccessibilityLabel">@string/error_a11y_label</item>
</style>

<style name="Widget.Material3.CompoundButton.CheckBox" parent="Base.Widget.Material3.CompoundButton.CheckBox" />
Expand Down

0 comments on commit 8dd9c7e

Please sign in to comment.