material-components-android icon indicating copy to clipboard operation
material-components-android copied to clipboard

[MaterialButtonToggleGroup] Updating corner radius programatically

Open Ekalips opened this issue 1 year ago • 0 comments
trafficstars

Is your feature request related to a problem? Please describe. It would be nice to have an ability to update the corner radius and/or treatment of MaterialButtonToggleGroup programatically (post creation) instead of being locked in to whatever values were set in the XML. The issue is that even if you change your button's ShapeAppearance after initial inflation, the MaterialButtonToggleGroup would not take the new values into consideration because it only updates those values when Views are added, which could be seen here

  void updateChildShapes() {
    for (int i = 0; i < childCount; i++) {
      MaterialButton button = getChildButton(i);
      ...
      ShapeAppearanceModel.Builder builder = button.getShapeAppearanceModel().toBuilder();
      CornerData newCornerData = getNewCornerData(i, firstVisibleChildIndex, lastVisibleChildIndex);
      updateBuilderWithCornerData(builder, newCornerData);

      button.setShapeAppearanceModel(builder.build());
    }
  }

@Nullable
  private CornerData getNewCornerData(
      int index, int firstVisibleChildIndex, int lastVisibleChildIndex) {
    CornerData cornerData = originalCornerData.get(index);
    ...
}

/**
   * This override prohibits Views other than {@link MaterialButton} to be added. It also makes
   * updates to the add button shape and margins.
   */
  @Override
  public void addView(View child, int index, ViewGroup.LayoutParams params) {
      ....
       ShapeAppearanceModel shapeAppearanceModel = buttonChild.getShapeAppearanceModel();
       originalCornerData.add(
        new CornerData(
            shapeAppearanceModel.getTopLeftCornerSize(),
            shapeAppearanceModel.getBottomLeftCornerSize(),
            shapeAppearanceModel.getTopRightCornerSize(),
            shapeAppearanceModel.getBottomRightCornerSize()));
      ...
}

@Override
  public void onViewRemoved(View child) {
       ...
     int indexOfChild = indexOfChild(child);
     if (indexOfChild >= 0) {
      originalCornerData.remove(indexOfChild);
    }
    ...
}

Describe the solution you'd like Ideally the solution would involve either a new function in MaterialButtonToggleGroup to invalidate cornerData (which is alright) or additional function to set ShapeAppearance to the MaterialButtonToggleGroup itself. Unfortunately it's probably not possible to do it fully automatically.

Ekalips avatar Jul 11 '24 13:07 Ekalips