简体   繁体   English

如何从资源设置Webview链接颜色

[英]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. 我有一些要加载到WebView HTML,我需要自定义CSS样式。 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: 在下面的示例中,使用linkColorManual工作,但是如果我将其切换为linkColor ,css样式将被忽略:

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: 这是我的color.xml文件中的相关行:

<?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? 如果直接从资源中加载颜色字符串,为什么它无法应用CSS?

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. 通过getResources().getString()检索Android Color资源时,我收到了8个字符的十六进制颜色,而不是 CSS可以解析的6位数字。 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). 前面的两个额外字符( #ff )表示Alpha(有关更多信息,请参见Android Color文档)。 To retrieve the 6 character CSS parsable color instead, I used the following: 要检索6个字符的CSS可分析颜色,我使用了以下方法:

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: 您应该像这样将颜色放在strings.xml中:

<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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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