[英]Android WebView link color
I am using WebView to show websites inside my application, and I was wondering is it possible to change link color and style which is by default blue and underlined? 我正在使用WebView在我的应用程序中显示网站,我想知道是否可以更改链接颜色和样式,默认为蓝色和下划线?
I searched about it but there are all questions and solutions about removing the highlight around the link, nothing about the link itself. 我搜索了它,但有关于删除链接周围的突出显示的所有问题和解决方案,没有关于链接本身。 I just want to know is there some solution as easy as TextView's android:textColorLink or will I need to alter the website body somehow? 我只想知道是否有一些解决方案就像TextView的android:textColorLink一样简单,还是我需要以某种方式改变网站体?
Thanks! 谢谢!
Okay, I managed to do it and wanted to share my way for the future visitors. 好的,我设法做到了,并想为未来的访客分享我的方式。
First I created a css file with the desired style, named style.css
, saved under assets folder 首先,我创建了一个带有所需样式的css文件,名为style.css
,保存在assets文件夹下
a {color:purple; text-decoration:none}
Then, in the code I loaded the page as follows where content
is the actual html content of the page 然后,在代码中我按如下方式加载页面,其中content
是页面的实际html内容
String htmlBody = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + content;
mWebView.loadDataWithBaseURL("file:///android_asset/", htmlBody, "text/html", "utf-8",
null);
That's it! 而已! Hope it helps somebody. 希望它对某人有帮助。
Here is an example of how to add html links and customize them: 以下是如何添加html链接并自定义它们的示例:
WebSettings webViewSettings = webView.getSettings();
webViewSettings.setDefaultFontSize(AppSettings.defaultFontSize);
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadDataWithBaseURL("file:///android_asset", Util.replaceLinkTags(myText), "text/html", "utf-8", null);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("file")) {
Intent intent = new Intent(MyActivity.this, MyActivity.class);
intent.putExtra("word", Uri.parse(url).getLastPathSegment());
startActivity(intent);
return true;
} else
return false;
}
});
public static String replaceLinkTags(String text) {
text = "<html><head>"
+ "<style type=\"text/css\">body{color:" + "#424242" + ";} a{color:#00B8D4; text-decoration:none; font-weight:bold;}"
+ "</style></head>"
+ "<body>" + text + "</body></html>";
String str;
while ((text.indexOf("\u0082") > 0)) {
if ((text.indexOf("\u0082") > 0) && (text.indexOf("\u0083") > 0)) {
str = text.substring(text.indexOf("\u0082") + 1, text.indexOf("\u0083"));
text = text.replaceAll("\u0082" + str + "\u0083", "<a href=\"" + str + "\">" + str + "</a>");
}
}
return text;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.