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
4 changes: 3 additions & 1 deletion android/capacitor/src/main/java/com/getcapacitor/Bridge.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
import org.json.JSONException;
import org.json.JSONObject;

import com.getcapacitor.util.WebColor;

/**
* The Bridge class is the main engine of Capacitor. It manages
* loading and communicating with all Plugins,
Expand Down Expand Up @@ -400,7 +402,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,27 @@
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(colorString);
} else {
// Convert to Android format #AARRGGBB from #RRGGBBAA
formattedColor = "#" + formattedColor.substring(7) + formattedColor.substring(1, 7);
return Color.parseColor(formattedColor);
}
}
}