Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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?

Thanks!

like image 771
ecem Avatar asked Sep 19 '13 20:09

ecem


2 Answers

Here is an example of how to add html links and customize them:

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;
}
like image 80
live-love Avatar answered Oct 22 '22 19:10

live-love


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

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

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.

like image 25
ecem Avatar answered Oct 22 '22 20:10

ecem