简体   繁体   中英

How to set Webview link color from resource

I have some HTML that I'm loading into a WebView and I need to customize the css styles. When it came to setting the link color directly from my Color resource I had some trouble. In the following example using linkColorManual worked but if I switched it to linkColor the css style was ignored:

String mime = "text/html";
String encoding = "utf-8";
String linkColor = getResources().getString(R.color.Link_Colour);
String linkColorManual = "#867970";
String html = "<!DOCTYPE HTML>\n<html>\n<head>\n<style>\n"
        + "body, html { font-family: 'sans-serif'; font-size:14px; color:#8B8D90;}\n"
        + "a {color:"+linkColorManual+";}\n"
        + "</style>\n</head>\n<body>" + post.getPostData().toString() + "</body>\n</html>";
WebView myWebView = (WebView) findViewById(R.id.post_content);
myWebView.loadDataWithBaseURL(post.getPostURL().toString(), html, mime, encoding, null);

This is the relevant line from my color.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    ...
    <color name="Link_Colour">#867970</color>
    ...
</resources>

I'd rather not copy paste this hex color throughout my app. Why does it fail to apply the css if I load the color string directly from the resource?

Found the solution:

When retrieving an Android Color resource via getResources().getString() , I received an 8 character hex color NOT a 6 digit one that CSS can parse. From the example above this meant:

linkColor = #ff867970;
linkColorManual = #867970;

The extra two characters ( #ff ) at the front represent the Alpha (see Android Color docs for more info). To retrieve the 6 character CSS parsable color instead, I used the following:

int linkColorInt = getResources().getColor(R.color.Link_Colour);
String linkColor = "#" + Integer.toHexString(linkColorInt & 0x00FFFFFF);

You should just put your color in strings.xml like this:

<string name="Link_Colour">#223344</string>

Or if you want to stick with color, do this

int color = getResource().getColor(R.color.xyz);
String linkColor = "#" + Integer.toHexString(color)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM