Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(android): Add WebColor utility for parsing color #3947

Merged
merged 9 commits into from
Dec 14, 2020
3 changes: 2 additions & 1 deletion android/capacitor/src/main/java/com/getcapacitor/Bridge.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.getcapacitor.cordova.MockCordovaWebViewImpl;
import com.getcapacitor.util.HostMask;
import com.getcapacitor.util.PermissionHelper;
import com.getcapacitor.util.WebColor;
import java.io.File;
import java.net.SocketTimeoutException;
import java.net.URL;
Expand Down Expand Up @@ -400,7 +401,7 @@ private void initWebView() {
String backgroundColor = this.config.getString("android.backgroundColor", this.config.getString("backgroundColor", null));
try {
if (backgroundColor != null) {
webView.setBackgroundColor(Color.parseColor(backgroundColor));
webView.setBackgroundColor(WebColor.parseColor(backgroundColor));
}
} catch (IllegalArgumentException ex) {
Logger.debug("WebView background color not applied");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.getcapacitor.util;

import android.graphics.Color;

public class WebColor {

/**
* Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception.
* @param colorString The hexadecimal color string. The format is an RGB or RGBA hex string.
* @return The corresponding color as an int.
*/
public static int parseColor(String colorString) {
String formattedColor = colorString;
if (colorString.charAt(0) != '#') {
formattedColor = "#" + formattedColor;
}

if (formattedColor.length() != 7 && formattedColor.length() != 9) {
throw new IllegalArgumentException("The encoded color space is invalid or unknown");
} else if (formattedColor.length() == 7) {
return Color.parseColor(formattedColor);
} else {
// Convert to Android format #AARRGGBB from #RRGGBBAA
formattedColor = "#" + formattedColor.substring(7) + formattedColor.substring(1, 7);
return Color.parseColor(formattedColor);
}
}
}