/* * Copyright (C) 2019 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. */ package com.google.android.material.button; import com.google.android.material.R; import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap; import android.content.Context; import android.content.res.TypedArray; import android.text.TextUtils.TruncateAt; import android.util.AttributeSet; import android.util.Log; import android.view.SoundEffectConstants; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.ToggleButton; import androidx.annotation.BoolRes; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.view.AccessibilityDelegateCompat; import androidx.core.view.ViewCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.CollectionItemInfoCompat; import com.google.android.material.internal.ThemeEnforcement; import com.google.android.material.shape.AbsoluteCornerSize; import com.google.android.material.shape.StateListCornerSize; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * A common container for a set of related, toggleable {@link MaterialButton}s. The {@link * MaterialButton}s in this group will be shown on a single line. * *
This layout currently only supports child views of type {@link MaterialButton}. Buttons can be * added to this view group via XML, as follows: * *
* <com.google.android.material.button.MaterialButtonToggleGroup * xmlns:android="http://schemas.android.com/apk/res/android" * android:id="@+id/toggle_button_group" * android:layout_width="wrap_content" * android:layout_height="wrap_content"> * * <com.google.android.material.button.MaterialButton * style="?attr/materialButtonOutlinedStyle" * android:layout_width="wrap_content" * android:layout_height="wrap_content" * android:text="@string/button_label_private"/> * <com.google.android.material.button.MaterialButton * style="?attr/materialButtonOutlinedStyle" * android:layout_width="wrap_content" * android:layout_height="wrap_content" * android:text="@string/button_label_team"/> * <com.google.android.material.button.MaterialButton * style="?attr/materialButtonOutlinedStyle" * android:layout_width="wrap_content" * android:layout_height="wrap_content" * android:text="@string/button_label_everyone"/> * <com.google.android.material.button.MaterialButton * style="?attr/materialButtonOutlinedStyle" * android:layout_width="wrap_content" * android:layout_height="wrap_content" * android:text="@string/button_label_custom"/> * * </com.google.android.material.button.MaterialButtonToggleGroup> ** *
Buttons can also be added to this view group programmatically via the {@link #addView(View)} * methods. * *
Note: Styling must applied to each child button individually. It is recommended to use the * {@code materialButtonOutlinedStyle} attribute for all child buttons. {@code * materialButtonOutlinedStyle} will most closely match the Material Design guidelines for this * component, and supports the checked state for child buttons. * *
Any {@link MaterialButton}s added to this view group are automatically marked as {@code * checkable}, and by default multiple buttons within the same group can be checked. To enforce that * only one button can be checked at a time, set the {@code app:singleSelection} attribute to {@code * true} on the MaterialButtonToggleGroup or call {@link #setSingleSelection(boolean) * setSingleSelection(true)}. * *
MaterialButtonToggleGroup is a {@link LinearLayout}. Using {@code * android:layout_width="MATCH_PARENT"} and removing {@code android:insetBottom} {@code * android:insetTop} on the children is recommended if using {@code VERTICAL}. * *
In order to cohesively group multiple buttons together, MaterialButtonToggleGroup overrides * the start and end margins of any children added to this layout such that child buttons are placed * directly adjacent to one another. * *
MaterialButtonToggleGroup also overrides any {@code shapeAppearance}, {@code * shapeAppearanceOverlay}, or {@code cornerRadius} attribute set on MaterialButton children such * that only the left-most corners of the first child and the right-most corners of the last child * retain their shape appearance or corner size. * *
For more information, see the component
* developer guidance and design
* guidelines.
*/
public class MaterialButtonToggleGroup extends MaterialButtonGroup {
/**
* Interface definition for a callback to be invoked when a {@link MaterialButton} is checked or
* unchecked in this group.
*/
public interface OnButtonCheckedListener {
/**
* Called when a {@link MaterialButton} in this group is checked or unchecked.
*
* @param group The group in which the MaterialButton's checked state was changed
* @param checkedId The unique identifier of the MaterialButton whose check state changed
* @param isChecked Whether the MaterialButton is currently checked
*/
void onButtonChecked(MaterialButtonToggleGroup group, @IdRes int checkedId, boolean isChecked);
}
private static final String LOG_TAG = "MButtonToggleGroup";
private static final int DEF_STYLE_RES =
R.style.Widget_MaterialComponents_MaterialButtonToggleGroup;
private final LinkedHashSet Components that add a listener should take care to remove it when finished via {@link
* #removeOnButtonCheckedListener(OnButtonCheckedListener)}.
*
* @param listener listener to add
*/
public void addOnButtonCheckedListener(@NonNull OnButtonCheckedListener listener) {
onButtonCheckedListeners.add(listener);
}
/**
* Remove a listener that was previously added via {@link
* #addOnButtonCheckedListener(OnButtonCheckedListener)}.
*
* @param listener listener to remove
*/
public void removeOnButtonCheckedListener(@NonNull OnButtonCheckedListener listener) {
onButtonCheckedListeners.remove(listener);
}
/** Remove all previously added {@link OnButtonCheckedListener}s. */
public void clearOnButtonCheckedListeners() {
onButtonCheckedListeners.clear();
}
/**
* Returns whether this group only allows a single button to be checked.
*
* @return whether this group only allows a single button to be checked
* @attr ref R.styleable#MaterialButtonToggleGroup_singleSelection
*/
public boolean isSingleSelection() {
return singleSelection;
}
/**
* Sets whether this group only allows a single button to be checked.
*
* Calling this method results in all the buttons in this group to become unchecked.
*
* @param singleSelection whether this group only allows a single button to be checked
* @attr ref R.styleable#MaterialButtonToggleGroup_singleSelection
*/
public void setSingleSelection(boolean singleSelection) {
if (this.singleSelection != singleSelection) {
this.singleSelection = singleSelection;
clearChecked();
}
updateChildrenA11yClassName();
}
private void updateChildrenA11yClassName() {
String className = getChildrenA11yClassName();
for (int i = 0; i < getChildCount(); i++) {
getChildButton(i).setA11yClassName(className);
}
}
@NonNull
private String getChildrenA11yClassName() {
return singleSelection ? RadioButton.class.getName() : ToggleButton.class.getName();
}
/**
* Sets whether we prevent all child buttons from being deselected.
*
* @attr ref R.styleable#MaterialButtonToggleGroup_selectionRequired
*/
public void setSelectionRequired(boolean selectionRequired) {
this.selectionRequired = selectionRequired;
}
/**
* Returns whether we prevent all child buttons from being deselected.
*
* @attr ref R.styleable#MaterialButtonToggleGroup_selectionRequired
*/
public boolean isSelectionRequired() {
return selectionRequired;
}
/**
* Sets whether this group only allows a single button to be checked.
*
* Calling this method results in all the buttons in this group to become unchecked.
*
* @param id boolean resource ID of whether this group only allows a single button to be checked
* @attr ref R.styleable#MaterialButtonToggleGroup_singleSelection
*/
public void setSingleSelection(@BoolRes int id) {
setSingleSelection(getResources().getBoolean(id));
}
private void setCheckedStateForView(@IdRes int viewId, boolean checked) {
View checkedView = findViewById(viewId);
if (checkedView instanceof MaterialButton) {
skipCheckedStateTracker = true;
((MaterialButton) checkedView).setChecked(checked);
skipCheckedStateTracker = false;
}
}
private boolean isChildVisible(int i) {
View child = getChildAt(i);
return child.getVisibility() != View.GONE;
}
private int getVisibleButtonCount() {
int count = 0;
for (int i = 0; i < getChildCount(); i++) {
if (this.getChildAt(i) instanceof MaterialButton && isChildVisible(i)) {
count++;
}
}
return count;
}
private int getIndexWithinVisibleButtons(@Nullable View child) {
if (!(child instanceof MaterialButton)) {
return -1;
}
int index = 0;
for (int i = 0; i < getChildCount(); i++) {
if (this.getChildAt(i) == child) {
return index;
}
if (this.getChildAt(i) instanceof MaterialButton && isChildVisible(i)) {
index++;
}
}
return -1;
}
private void checkInternal(@IdRes int buttonId, boolean checked) {
if (buttonId == View.NO_ID) {
Log.e(LOG_TAG, "Button ID is not valid: " + buttonId);
return;
}
Set