yanchenko
yanchenko

Reputation: 57216

Changing text color in a WebView?

There's a method for altering background color but not font.
Any ideas?

Upvotes: 28

Views: 39977

Answers (8)

Ismail Iqbal
Ismail Iqbal

Reputation: 2580

This worked for me

myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
    view.loadUrl(
        "javascript:document.body.style.setProperty(\"color\", \"white\");"
    );
  }
});

Upvotes: 15

Vladimir Salguero
Vladimir Salguero

Reputation: 5947

You can concatenate your answer one body tag HTML with CSS style hex color, this is an example using a JSON response

First: function for decode JSON to HTML format

public String stripHtml(String html) {
    return Html.fromHtml(html).toString();
}

Second: Load data in WebView (no url)

 String string_html;
 string_html = "<body style="color:#535362;">" + youStringHTML + "</body>";
 webView.loadDataWithBaseURL(null, stripHtml(string_html), "text/html", "utf-8", null);

Upvotes: 1

djunod
djunod

Reputation: 4976

I had to put it in the onPageFinished method.

_webView.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView view, String url) {
        _webView.loadUrl(
            "javascript:document.body.style.setProperty(\"color\", \"white\");"
        );
    }
});

Upvotes: 26

Jess Smith
Jess Smith

Reputation: 167

@rafraph's answer didn't work for me. I had to use

webView.loadUrl("javascript:document.body.style.setProperty(\"color\", \"white\");");

Upvotes: 2

RafaelJan
RafaelJan

Reputation: 3606

This is the easiest way I found (change the text color to white for example):

webview.loadUrl("javascript:document.body.style.color=\"white\";");

Upvotes: 6

OWADVL
OWADVL

Reputation: 11154

something like

String text = "<html><head>"
          + "<style type=\"text/css\">body{color: #fff; background-color: #000;}"
          + "</style></head>"
          + "<body>"                          
          + your_string_text_here
          + "</body></html>";

webview1.loadData(text, "text/html", "utf-8");

Upvotes: 40

paiego
paiego

Reputation: 3787

When the buffer is SPANNABLE, modifying the HTML directly is an ideal solution. The font, color, typeface, style can all be affected through HTML:

String szMessage = "<font face='trebuchet' size=30><a href=zz><b>click me</b></a></font>";

TextView tv = (TextView)findViewById(R.id.tv_message);
tv.setText(Html.fromHtml(szMessage), BufferType.SPANNABLE);

Upvotes: 2

MattC
MattC

Reputation: 12327

I'm not sure I understand. The WebView just displays the HTML you give it so you would just use normal HTML/CSS to modify the content displayed within.

Upvotes: 12

Related Questions