/
DynamicColors.java
424 lines (382 loc) · 16.6 KB
/
DynamicColors.java
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
413
414
415
416
417
418
419
420
421
422
423
424
/*
* 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.material.color;
import com.google.android.material.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import androidx.annotation.ChecksSdkIntAtLeast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;
import androidx.core.os.BuildCompat;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/** Utility for applying dynamic colors to application/activities. */
public class DynamicColors {
private static final int[] DYNAMIC_COLOR_THEME_OVERLAY_ATTRIBUTE =
new int[] {R.attr.dynamicColorThemeOverlay};
private static final DeviceSupportCondition DEFAULT_DEVICE_SUPPORT_CONDITION =
new DeviceSupportCondition() {
@Override
public boolean isSupported() {
return true;
}
};
@SuppressLint("PrivateApi")
private static final DeviceSupportCondition SAMSUNG_DEVICE_SUPPORT_CONDITION =
new DeviceSupportCondition() {
private Long version;
@Override
public boolean isSupported() {
if (version == null) {
try {
Method method = Build.class.getDeclaredMethod("getLong", String.class);
method.setAccessible(true);
version = (long) method.invoke(null, "ro.build.version.oneui");
} catch (Exception e) {
version = -1L;
}
}
return version >= 40100L;
}
};
private static final Map<String, DeviceSupportCondition> DYNAMIC_COLOR_SUPPORTED_MANUFACTURERS;
static {
Map<String, DeviceSupportCondition> deviceMap = new HashMap<>();
deviceMap.put("fcnt", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("google", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("hmd global", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("infinix", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("infinix mobility limited", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("itel", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("kyocera", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("lenovo", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("lge", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("motorola", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("nothing", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("oneplus", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("oppo", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("realme", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("robolectric", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("samsung", SAMSUNG_DEVICE_SUPPORT_CONDITION);
deviceMap.put("sharp", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("sony", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("tcl", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("tecno", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("tecno mobile limited", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("vivo", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("xiaomi", DEFAULT_DEVICE_SUPPORT_CONDITION);
DYNAMIC_COLOR_SUPPORTED_MANUFACTURERS = Collections.unmodifiableMap(deviceMap);
}
private static final Map<String, DeviceSupportCondition> DYNAMIC_COLOR_SUPPORTED_BRANDS;
static {
Map<String, DeviceSupportCondition> deviceMap = new HashMap<>();
deviceMap.put("asus", DEFAULT_DEVICE_SUPPORT_CONDITION);
deviceMap.put("jio", DEFAULT_DEVICE_SUPPORT_CONDITION);
DYNAMIC_COLOR_SUPPORTED_BRANDS = Collections.unmodifiableMap(deviceMap);
}
private static final int USE_DEFAULT_THEME_OVERLAY = 0;
private DynamicColors() {}
/**
* Applies dynamic colors to all activities with the theme overlay designated by the theme
* attribute {@code dynamicColorThemeOverlay} by registering a {@link ActivityLifecycleCallbacks}
* to your application.
*
* @see #applyToActivitiesIfAvailable(Application, DynamicColorsOptions) for more detailed info
* and examples.
* @param application The target application.
*/
public static void applyToActivitiesIfAvailable(@NonNull Application application) {
applyToActivitiesIfAvailable(application, new DynamicColorsOptions.Builder().build());
}
/**
* Applies dynamic colors to all activities with the given theme overlay by registering a {@link
* ActivityLifecycleCallbacks} to your application.
*
* @param application The target application.
* @param theme The resource ID of the theme overlay that provides dynamic color definition.
* @deprecated Use {@link #applyToActivitiesIfAvailable(Application, DynamicColorsOptions)}
* instead.
*/
@Deprecated
public static void applyToActivitiesIfAvailable(
@NonNull Application application, @StyleRes int theme) {
applyToActivitiesIfAvailable(
application, new DynamicColorsOptions.Builder().setThemeOverlay(theme).build());
}
/**
* Applies dynamic colors to all activities with the theme overlay designated by the theme
* attribute {@code dynamicColorThemeOverlay} according to the given precondition by registering a
* {@link ActivityLifecycleCallbacks} to your application.
*
* @param application The target application.
* @param precondition The precondition to decide if dynamic colors should be applied.
* @deprecated Use {@link #applyToActivitiesIfAvailable(Application, DynamicColorsOptions)}
* instead.
*/
@Deprecated
public static void applyToActivitiesIfAvailable(
@NonNull Application application, @NonNull Precondition precondition) {
applyToActivitiesIfAvailable(
application, new DynamicColorsOptions.Builder().setPrecondition(precondition).build());
}
/**
* Applies dynamic colors to all activities with the given theme overlay according to the given
* precondition by registering a {@link ActivityLifecycleCallbacks} to your application.
*
* @param application The target application.
* @param theme The resource ID of the theme overlay that provides dynamic color definition.
* @param precondition The precondition to decide if dynamic colors should be applied.
* @deprecated Use {@link #applyToActivitiesIfAvailable(Application, DynamicColorsOptions)}
* instead.
*/
@Deprecated
public static void applyToActivitiesIfAvailable(
@NonNull Application application, @StyleRes int theme, @NonNull Precondition precondition) {
applyToActivitiesIfAvailable(
application,
new DynamicColorsOptions.Builder()
.setThemeOverlay(theme)
.setPrecondition(precondition)
.build());
}
/**
* Applies dynamic colors to all activities based on the provided {@link DynamicColorsOptions}, by
* registering a {@link ActivityLifecycleCallbacks} to your application.
*
* <p>A normal usage of this method should happen only once in {@link Application#onCreate()} or
* any methods that run before any of your activities are created. For example:
*
* <pre>
* public class YourApplication extends Application {
* @Override
* public void onCreate() {
* super.onCreate();
* DynamicColors.applyToActivitiesWithCallbacks(this);
* }
* }
* </pre>
*
* This method will try to apply the given dynamic color theme overlay in every activity's {@link
* ActivityLifecycleCallbacks#onActivityPreCreated(Activity, Bundle)} callback. Therefore, if you
* are applying any other theme overlays after that, you will need to be careful about not
* overriding the colors or you may lose the dynamic color support.
*
* @param application The target application.
* @param dynamicColorsOptions The dynamic colors options object that specifies the theme resource
* ID, precondition to decide if dynamic colors should be applied and the callback function
* for after dynamic colors have been applied.
*/
public static void applyToActivitiesIfAvailable(
@NonNull Application application, @NonNull DynamicColorsOptions dynamicColorsOptions) {
application.registerActivityLifecycleCallbacks(
new DynamicColorsActivityLifecycleCallbacks(dynamicColorsOptions));
}
/**
* Applies dynamic colors to the given activity with the theme overlay designated by the theme
* attribute {@code dynamicColorThemeOverlay}.
*
* @param activity The target activity.
* @deprecated Use {@link #applyToActivityIfAvailable(Activity)} instead.
*/
@Deprecated
public static void applyIfAvailable(@NonNull Activity activity) {
applyToActivityIfAvailable(activity);
}
/**
* Applies dynamic colors to the given activity with the given theme overlay.
*
* @param activity The target activity.
* @param theme The resource ID of the theme overlay that provides dynamic color definition.
* @deprecated Use {@link #applyToActivityIfAvailable(Activity, DynamicColorsOptions)} instead.
*/
@Deprecated
public static void applyIfAvailable(@NonNull Activity activity, @StyleRes int theme) {
applyToActivityIfAvailable(
activity, new DynamicColorsOptions.Builder().setThemeOverlay(theme).build());
}
/**
* Applies dynamic colors to the given activity with the theme overlay designated by the theme
* attribute {@code dynamicColorThemeOverlay} according to the given precondition.
*
* @param activity The target activity.
* @param precondition The precondition to decide if dynamic colors should be applied.
* @deprecated Use {@link #applyToActivityIfAvailable(Activity, DynamicColorsOptions)} instead.
*/
@Deprecated
public static void applyIfAvailable(
@NonNull Activity activity, @NonNull Precondition precondition) {
applyToActivityIfAvailable(
activity, new DynamicColorsOptions.Builder().setPrecondition(precondition).build());
}
/**
* Applies dynamic colors to the given activity.
*
* @param activity The target activity.
* @see #applyToActivityIfAvailable(Activity, DynamicColorsOptions)
*/
public static void applyToActivityIfAvailable(@NonNull Activity activity) {
applyToActivityIfAvailable(activity, new DynamicColorsOptions.Builder().build());
}
/**
* Applies dynamic colors to the given activity with {@link DynamicColorsOptions} provided.
*
* @param activity The target activity.
* @param dynamicColorsOptions The dynamic colors options object that specifies the theme resource
* ID, precondition to decide if dynamic colors should be applied and the callback function
* for after dynamic colors have been applied.
*/
public static void applyToActivityIfAvailable(
@NonNull Activity activity, @NonNull DynamicColorsOptions dynamicColorsOptions) {
applyToActivityIfAvailable(
activity,
dynamicColorsOptions.getThemeOverlay(),
dynamicColorsOptions.getPrecondition(),
dynamicColorsOptions.getOnAppliedCallback());
}
private static void applyToActivityIfAvailable(
@NonNull Activity activity,
@StyleRes int theme,
@NonNull Precondition precondition,
@NonNull OnAppliedCallback onAppliedCallback) {
if (!isDynamicColorAvailable()) {
return;
}
if (theme == USE_DEFAULT_THEME_OVERLAY) {
theme = getDefaultThemeOverlay(activity);
}
if (theme != 0 && precondition.shouldApplyDynamicColors(activity, theme)) {
ThemeUtils.applyThemeOverlay(activity, theme);
onAppliedCallback.onApplied(activity);
}
}
/**
* Wraps the given context with the theme overlay designated by the theme attribute {@code
* dynamicColorThemeOverlay}. The returned context can be used to create views with dynamic color
* support.
*
* <p>If dynamic color support or the dynamic color theme overlay is not available, the original
* context will be returned.
*
* @param originalContext The original context.
*/
@NonNull
public static Context wrapContextIfAvailable(@NonNull Context originalContext) {
return wrapContextIfAvailable(originalContext, USE_DEFAULT_THEME_OVERLAY);
}
/**
* Wraps the given context with the given theme overlay. The returned context can be used to
* create views with dynamic color support.
*
* <p>If dynamic color support is not available, the original context will be returned.
*
* @param originalContext The original context.
* @param theme The resource ID of the theme overlay that provides dynamic color definition.
*/
@NonNull
public static Context wrapContextIfAvailable(
@NonNull Context originalContext, @StyleRes int theme) {
if (!isDynamicColorAvailable()) {
return originalContext;
}
if (theme == USE_DEFAULT_THEME_OVERLAY) {
theme = getDefaultThemeOverlay(originalContext);
}
return theme == 0 ? originalContext : new ContextThemeWrapper(originalContext, theme);
}
/** Returns {@code true} if dynamic colors are available on the current SDK level. */
@SuppressLint("DefaultLocale")
@ChecksSdkIntAtLeast(api = VERSION_CODES.S)
public static boolean isDynamicColorAvailable() {
if (VERSION.SDK_INT < VERSION_CODES.S) {
return false;
}
if (BuildCompat.isAtLeastT()) {
return true;
}
DeviceSupportCondition deviceSupportCondition =
DYNAMIC_COLOR_SUPPORTED_MANUFACTURERS.get(Build.MANUFACTURER.toLowerCase());
if (deviceSupportCondition == null) {
deviceSupportCondition = DYNAMIC_COLOR_SUPPORTED_BRANDS.get(Build.BRAND.toLowerCase());
}
return deviceSupportCondition != null && deviceSupportCondition.isSupported();
}
private static int getDefaultThemeOverlay(@NonNull Context context) {
TypedArray dynamicColorAttributes =
context.obtainStyledAttributes(DYNAMIC_COLOR_THEME_OVERLAY_ATTRIBUTE);
final int theme = dynamicColorAttributes.getResourceId(0, 0);
dynamicColorAttributes.recycle();
return theme;
}
/** The interface that provides a precondition to decide if dynamic colors should be applied. */
public interface Precondition {
/**
* Return {@code true} if dynamic colors should be applied on the given activity with the given
* theme overlay.
*/
boolean shouldApplyDynamicColors(@NonNull Activity activity, @StyleRes int theme);
}
/** The interface that provides a callback method after dynamic colors have been applied. */
public interface OnAppliedCallback {
/** The callback method after dynamic colors have been applied. */
void onApplied(@NonNull Activity activity);
}
private static class DynamicColorsActivityLifecycleCallbacks
implements ActivityLifecycleCallbacks {
private final DynamicColorsOptions dynamicColorsOptions;
DynamicColorsActivityLifecycleCallbacks(@NonNull DynamicColorsOptions options) {
this.dynamicColorsOptions = options;
}
@Override
public void onActivityPreCreated(
@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
applyToActivityIfAvailable(
activity,
dynamicColorsOptions.getThemeOverlay(),
dynamicColorsOptions.getPrecondition(),
dynamicColorsOptions.getOnAppliedCallback());
}
@Override
public void onActivityCreated(
@NonNull Activity activity, @Nullable Bundle savedInstanceState) {}
@Override
public void onActivityStarted(@NonNull Activity activity) {}
@Override
public void onActivityResumed(@NonNull Activity activity) {}
@Override
public void onActivityPaused(@NonNull Activity activity) {}
@Override
public void onActivityStopped(@NonNull Activity activity) {}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {}
}
private interface DeviceSupportCondition {
boolean isSupported();
}
}