Skip to content

Commit

Permalink
feat(android): Add WebColor utility for parsing color (#3947)
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasvidas authored Dec 14, 2020
1 parent b2816d8 commit 3746404
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
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);
}
}
}

0 comments on commit 3746404

Please sign in to comment.