summaryrefslogtreecommitdiff
path: root/main/java/com/google/android/setupcompat/template/FooterButtonStyleUtils.java
blob: ef45b5c0fa1325e3028e524391ce8a7381ece4df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/*
 * Copyright (C) 2021 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.setupcompat.template;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.InsetDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.util.StateSet;
import android.util.TypedValue;
import android.widget.Button;
import androidx.annotation.ColorInt;
import androidx.annotation.VisibleForTesting;
import com.google.android.setupcompat.R;
import com.google.android.setupcompat.internal.FooterButtonPartnerConfig;
import com.google.android.setupcompat.internal.Preconditions;
import com.google.android.setupcompat.partnerconfig.PartnerConfig;
import com.google.android.setupcompat.partnerconfig.PartnerConfigHelper;

/** Utils for updating the button style. */
public class FooterButtonStyleUtils {
  private static final float DEFAULT_DISABLED_ALPHA = 0.26f;

  /** Apply the partner primary button style to given {@code button}. */
  public static void applyPrimaryButtonPartnerResource(
      Context context, Button button, boolean applyDynamicColor) {

    FooterButtonPartnerConfig footerButtonPartnerConfig =
        new FooterButtonPartnerConfig.Builder(null)
            .setPartnerTheme(R.style.SucPartnerCustomizationButton_Primary)
            .setButtonBackgroundConfig(PartnerConfig.CONFIG_FOOTER_PRIMARY_BUTTON_BG_COLOR)
            .setButtonDisableAlphaConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_DISABLED_ALPHA)
            .setButtonDisableBackgroundConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_DISABLED_BG_COLOR)
            .setButtonRadiusConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_RADIUS)
            .setButtonRippleColorAlphaConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_RIPPLE_COLOR_ALPHA)
            .setTextColorConfig(PartnerConfig.CONFIG_FOOTER_PRIMARY_BUTTON_TEXT_COLOR)
            .setTextSizeConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_TEXT_SIZE)
            .setButtonMinHeight(PartnerConfig.CONFIG_FOOTER_BUTTON_MIN_HEIGHT)
            .setTextTypeFaceConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_FONT_FAMILY)
            .setTextStyleConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_TEXT_STYLE)
            .build();
    applyButtonPartnerResources(
        context,
        button,
        applyDynamicColor,
        /* isButtonIconAtEnd= */ true,
        footerButtonPartnerConfig);
  }

  /** Apply the partner secondary button style to given {@code button}. */
  public static void applySecondaryButtonPartnerResource(
      Context context, Button button, boolean applyDynamicColor) {

    int defaultTheme = R.style.SucPartnerCustomizationButton_Secondary;
    int color =
        PartnerConfigHelper.get(context)
            .getColor(context, PartnerConfig.CONFIG_FOOTER_SECONDARY_BUTTON_BG_COLOR);
    if (color != Color.TRANSPARENT) {
      defaultTheme = R.style.SucPartnerCustomizationButton_Primary;
    }
    // Setup button partner config
    FooterButtonPartnerConfig footerButtonPartnerConfig =
        new FooterButtonPartnerConfig.Builder(null)
            .setPartnerTheme(defaultTheme)
            .setButtonBackgroundConfig(PartnerConfig.CONFIG_FOOTER_SECONDARY_BUTTON_BG_COLOR)
            .setButtonDisableAlphaConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_DISABLED_ALPHA)
            .setButtonDisableBackgroundConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_DISABLED_BG_COLOR)
            .setButtonRadiusConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_RADIUS)
            .setButtonRippleColorAlphaConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_RIPPLE_COLOR_ALPHA)
            .setTextColorConfig(PartnerConfig.CONFIG_FOOTER_SECONDARY_BUTTON_TEXT_COLOR)
            .setTextSizeConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_TEXT_SIZE)
            .setButtonMinHeight(PartnerConfig.CONFIG_FOOTER_BUTTON_MIN_HEIGHT)
            .setTextTypeFaceConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_FONT_FAMILY)
            .setTextStyleConfig(PartnerConfig.CONFIG_FOOTER_BUTTON_TEXT_STYLE)
            .build();
    applyButtonPartnerResources(
        context,
        button,
        applyDynamicColor,
        /* isButtonIconAtEnd= */ false,
        footerButtonPartnerConfig);
  }

  static void applyButtonPartnerResources(
      Context context,
      Button button,
      boolean applyDynamicColor,
      boolean isButtonIconAtEnd,
      FooterButtonPartnerConfig footerButtonPartnerConfig) {

    // If dynamic color enabled, these colors won't be overrode by partner config.
    // Instead, these colors align with the current theme colors.
    if (!applyDynamicColor) {
      // use default disable color util we support the partner disable text color
      if (button.isEnabled()) {
        FooterButtonStyleUtils.updateButtonTextEnabledColorWithPartnerConfig(
            context, button, footerButtonPartnerConfig.getButtonTextColorConfig());
      }
      FooterButtonStyleUtils.updateButtonBackgroundWithPartnerConfig(
          context,
          button,
          footerButtonPartnerConfig.getButtonBackgroundConfig(),
          footerButtonPartnerConfig.getButtonDisableAlphaConfig(),
          footerButtonPartnerConfig.getButtonDisableBackgroundConfig());
    }
    FooterButtonStyleUtils.updateButtonRippleColorWithPartnerConfig(
        context,
        button,
        applyDynamicColor,
        footerButtonPartnerConfig.getButtonTextColorConfig(),
        footerButtonPartnerConfig.getButtonRippleColorAlphaConfig());
    FooterButtonStyleUtils.updateButtonTextSizeWithPartnerConfig(
        context, button, footerButtonPartnerConfig.getButtonTextSizeConfig());
    FooterButtonStyleUtils.updateButtonMinHeightWithPartnerConfig(
        context, button, footerButtonPartnerConfig.getButtonMinHeightConfig());
    FooterButtonStyleUtils.updateButtonTypeFaceWithPartnerConfig(
        context,
        button,
        footerButtonPartnerConfig.getButtonTextTypeFaceConfig(),
        footerButtonPartnerConfig.getButtonTextStyleConfig());
    FooterButtonStyleUtils.updateButtonRadiusWithPartnerConfig(
        context, button, footerButtonPartnerConfig.getButtonRadiusConfig());
    FooterButtonStyleUtils.updateButtonIconWithPartnerConfig(
        context, button, footerButtonPartnerConfig.getButtonIconConfig(), isButtonIconAtEnd);
  }

  static void updateButtonTextEnabledColorWithPartnerConfig(
      Context context, Button button, PartnerConfig buttonEnableTextColorConfig) {
    @ColorInt
    int color = PartnerConfigHelper.get(context).getColor(context, buttonEnableTextColorConfig);
    updateButtonTextEnabledColor(button, color);
  }

  static void updateButtonTextEnabledColor(Button button, @ColorInt int textColor) {
    if (textColor != Color.TRANSPARENT) {
      button.setTextColor(ColorStateList.valueOf(textColor));
    }
  }

  static void updateButtonTextDisableColor(Button button, ColorStateList disabledTextColor) {
    // TODO : add disable footer button text color partner config

    // disable state will use the default disable state color
    button.setTextColor(disabledTextColor);
  }

  @TargetApi(VERSION_CODES.Q)
  static void updateButtonBackgroundWithPartnerConfig(
      Context context,
      Button button,
      PartnerConfig buttonBackgroundConfig,
      PartnerConfig buttonDisableAlphaConfig,
      PartnerConfig buttonDisableBackgroundConfig) {
    Preconditions.checkArgument(
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q,
        "Update button background only support on sdk Q or higher");
    @ColorInt
    int color = PartnerConfigHelper.get(context).getColor(context, buttonBackgroundConfig);
    float disabledAlpha =
        PartnerConfigHelper.get(context).getFraction(context, buttonDisableAlphaConfig, 0f);
    @ColorInt
    int disabledColor =
        PartnerConfigHelper.get(context).getColor(context, buttonDisableBackgroundConfig);

    updateButtonBackgroundTintList(context, button, color, disabledAlpha, disabledColor);
  }

  @TargetApi(VERSION_CODES.Q)
  static void updateButtonBackgroundTintList(
      Context context,
      Button button,
      @ColorInt int color,
      float disabledAlpha,
      @ColorInt int disabledColor) {
    int[] DISABLED_STATE_SET = {-android.R.attr.state_enabled};
    int[] ENABLED_STATE_SET = {};

    if (color != Color.TRANSPARENT) {
      if (disabledAlpha <= 0f) {
        // if no partner resource, fallback to theme disable alpha
        TypedArray a = context.obtainStyledAttributes(new int[] {android.R.attr.disabledAlpha});
        float alpha = a.getFloat(0, DEFAULT_DISABLED_ALPHA);
        a.recycle();
        disabledAlpha = alpha;
      }
      if (disabledColor == Color.TRANSPARENT) {
        // if no partner resource, fallback to button background color
        disabledColor = color;
      }

      // Set text color for ripple.
      ColorStateList colorStateList =
          new ColorStateList(
              new int[][] {DISABLED_STATE_SET, ENABLED_STATE_SET},
              new int[] {convertRgbToArgb(disabledColor, disabledAlpha), color});

      // b/129482013: When a LayerDrawable is mutated, a new clone of its children drawables are
      // created, but without copying the state from the parent drawable. So even though the
      // parent is getting the correct drawable state from the view, the children won't get those
      // states until a state change happens.
      // As a workaround, we mutate the drawable and forcibly set the state to empty, and then
      // refresh the state so the children will have the updated states.
      button.getBackground().mutate().setState(new int[0]);
      button.refreshDrawableState();
      button.setBackgroundTintList(colorStateList);
    }
  }

  @TargetApi(VERSION_CODES.Q)
  static void updateButtonRippleColorWithPartnerConfig(
      Context context,
      Button button,
      boolean applyDynamicColor,
      PartnerConfig buttonTextColorConfig,
      PartnerConfig buttonRippleColorAlphaConfig) {
    if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {

      @ColorInt int textDefaultColor;
      if (applyDynamicColor) {
        // Get dynamic text color
        textDefaultColor = button.getTextColors().getDefaultColor();
      } else {
        // Get partner text color.
        textDefaultColor =
            PartnerConfigHelper.get(context).getColor(context, buttonTextColorConfig);
      }
      float alpha =
          PartnerConfigHelper.get(context).getFraction(context, buttonRippleColorAlphaConfig);
      updateButtonRippleColor(button, textDefaultColor, alpha);
    }
  }

  private static void updateButtonRippleColor(
      Button button, @ColorInt int textColor, float rippleAlpha) {
    // RippleDrawable is available after sdk 21. And because on lower sdk the RippleDrawable is
    // unavailable. Since Stencil customization provider only works on Q+, there is no need to
    // perform any customization for versions 21.
    if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      RippleDrawable rippleDrawable = getRippleDrawable(button);
      if (rippleDrawable == null) {
        return;
      }

      int[] pressedState = {android.R.attr.state_pressed};

      // Set text color for ripple.
      ColorStateList colorStateList =
          new ColorStateList(
              new int[][] {pressedState, StateSet.NOTHING},
              new int[] {convertRgbToArgb(textColor, rippleAlpha), Color.TRANSPARENT});
      rippleDrawable.setColor(colorStateList);
    }
  }

  static void updateButtonTextSizeWithPartnerConfig(
      Context context, Button button, PartnerConfig buttonTextSizeConfig) {
    float size = PartnerConfigHelper.get(context).getDimension(context, buttonTextSizeConfig);
    if (size > 0) {
      button.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
    }
  }

  static void updateButtonMinHeightWithPartnerConfig(
      Context context, Button button, PartnerConfig buttonMinHeightConfig) {
    if (PartnerConfigHelper.get(context).isPartnerConfigAvailable(buttonMinHeightConfig)) {
      float size = PartnerConfigHelper.get(context).getDimension(context, buttonMinHeightConfig);
      if (size > 0) {
        button.setMinHeight((int) size);
      }
    }
  }

  static void updateButtonTypeFaceWithPartnerConfig(
      Context context,
      Button button,
      PartnerConfig buttonTextTypeFaceConfig,
      PartnerConfig buttonTextStyleConfig) {
    String fontFamilyName =
        PartnerConfigHelper.get(context).getString(context, buttonTextTypeFaceConfig);

    int textStyleValue = Typeface.NORMAL;
    if (PartnerConfigHelper.get(context).isPartnerConfigAvailable(buttonTextStyleConfig)) {
      textStyleValue =
          PartnerConfigHelper.get(context)
              .getInteger(context, buttonTextStyleConfig, Typeface.NORMAL);
    }
    Typeface font = Typeface.create(fontFamilyName, textStyleValue);
    if (font != null) {
      button.setTypeface(font);
    }
  }

  static void updateButtonRadiusWithPartnerConfig(
      Context context, Button button, PartnerConfig buttonRadiusConfig) {
    if (Build.VERSION.SDK_INT >= VERSION_CODES.N) {
      float radius = PartnerConfigHelper.get(context).getDimension(context, buttonRadiusConfig);
      GradientDrawable gradientDrawable = getGradientDrawable(button);
      if (gradientDrawable != null) {
        gradientDrawable.setCornerRadius(radius);
      }
    }
  }

  static void updateButtonIconWithPartnerConfig(
      Context context, Button button, PartnerConfig buttonIconConfig, boolean isButtonIconAtEnd) {
    if (button == null) {
      return;
    }
    Drawable icon = null;
    if (buttonIconConfig != null) {
      icon = PartnerConfigHelper.get(context).getDrawable(context, buttonIconConfig);
    }
    setButtonIcon(button, icon, isButtonIconAtEnd);
  }

  private static void setButtonIcon(Button button, Drawable icon, boolean isButtonIconAtEnd) {
    if (button == null) {
      return;
    }

    if (icon != null) {
      // TODO: restrict the icons to a reasonable size
      int h = icon.getIntrinsicHeight();
      int w = icon.getIntrinsicWidth();
      icon.setBounds(0, 0, w, h);
    }

    Drawable iconStart = null;
    Drawable iconEnd = null;
    if (isButtonIconAtEnd) {
      iconEnd = icon;
    } else {
      iconStart = icon;
    }
    if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
      button.setCompoundDrawablesRelative(iconStart, null, iconEnd, null);
    } else {
      button.setCompoundDrawables(iconStart, null, iconEnd, null);
    }
  }

  static void updateButtonBackground(Button button, @ColorInt int color) {
    button.getBackground().mutate().setColorFilter(color, Mode.SRC_ATOP);
  }

  @VisibleForTesting
  public static GradientDrawable getGradientDrawable(Button button) {
    // RippleDrawable is available after sdk 21, InsetDrawable#getDrawable is available after
    // sdk 19. So check the sdk is higher than sdk 21 and since Stencil customization provider only
    // works on Q+, there is no need to perform any customization for versions 21.
    if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      Drawable drawable = button.getBackground();
      if (drawable instanceof InsetDrawable) {
        LayerDrawable layerDrawable = (LayerDrawable) ((InsetDrawable) drawable).getDrawable();
        return (GradientDrawable) layerDrawable.getDrawable(0);
      } else if (drawable instanceof RippleDrawable) {
        if (((RippleDrawable) drawable).getDrawable(0) instanceof GradientDrawable) {
          return (GradientDrawable) ((RippleDrawable) drawable).getDrawable(0);
        }
        InsetDrawable insetDrawable = (InsetDrawable) ((RippleDrawable) drawable).getDrawable(0);
        return (GradientDrawable) insetDrawable.getDrawable();
      }
    }
    return null;
  }

  static RippleDrawable getRippleDrawable(Button button) {
    // RippleDrawable is available after sdk 21. And because on lower sdk the RippleDrawable is
    // unavailable. Since Stencil customization provider only works on Q+, there is no need to
    // perform any customization for versions 21.
    if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      Drawable drawable = button.getBackground();
      if (drawable instanceof InsetDrawable) {
        return (RippleDrawable) ((InsetDrawable) drawable).getDrawable();
      } else if (drawable instanceof RippleDrawable) {
        return (RippleDrawable) drawable;
      }
    }
    return null;
  }

  @ColorInt
  private static int convertRgbToArgb(@ColorInt int color, float alpha) {
    return Color.argb((int) (alpha * 255), Color.red(color), Color.green(color), Color.blue(color));
  }

  private FooterButtonStyleUtils() {}
}