I have a TextView that gets it's data set by calling this:
tv.setText(Html.fromHtml(myText));
The string myText contains partially formatted html data. For example, it might have font tags, but not have any url links formatted using <a href=...> tags. I was hoping to use the Linkify.addLinks(...) to do that since my text could include other types of links that Linkify would convert for me appropriately. So I wrote my code to look like this:
String myText = "<font color=\"red\">Red text</font> and Url: www.google.com";
tv.setText(Html.fromHtml(myText));
Linkify.addLinks(tv, Linkify.ALL);
tv.setMovementMethod(LinkMovementMethod.getInstance());
This does not work properly. Meaning that it processes the font tags but Linkify does not convert urls to UrlSpan properly.
Alternatively, if I call setText() without the Html.fromHtml(..), Linkify works but then I lose all the text formatted from the html font tags. Somehow they both seem to be conflicting and I can have only one or the other.
Now here's the interesting part that I dont understand. If I remove the Linkify code from java and go to my layout xml and put the following lines in there, all seems to be working (Linkify and fromHtml both end up playing nice together... somehow)
<TextView
...
android:autoLink="all"
android:linksClickable="true"
...
/>
Can someone explain to me why that would make everything work??
I looked into the source code for TextView's setMovementMethod() and it eventually ends up calling:
setFocusable(true);
setClickable(true);
setLongClickable(true);
That should theoretically make everything work and behave the same as the xml layout code. I tried switching the order of calling Linkify.addLinks(..) before setText(Html.fromHtml(..)) in the java code, but that didn't make a difference.
Any ideas as to why combining Linkify.addLinks() and Html.fromHtml() in java would cause this behavior... but not in the xml layout?
It's because Html.fromHtml and Linkify.addLinks removes previous spans before processing the text.
Use this code to get it work:
public static Spannable linkifyHtml(String html, int linkifyMask) {
Spanned text = Html.fromHtml(html);
URLSpan[] currentSpans = text.getSpans(0, text.length(), URLSpan.class);
SpannableString buffer = new SpannableString(text);
Linkify.addLinks(buffer, linkifyMask);
for (URLSpan span : currentSpans) {
int end = text.getSpanEnd(span);
int start = text.getSpanStart(span);
buffer.setSpan(span, start, end, 0);
}
return buffer;
}
You can try this one:
First set the text in to your TextView.
tv.setText(myText);
Convert the links with Linkify
Linkify.addLinks(tv, Linkify.ALL);
and finally replace the text with Html.fromHtml but using the Linkified text from your EditText.
tv.setText(Html.fromHtml(tv.getText().toString()));
100% works solution (kotlin).
Create class for store HtmlLink before Linkify
class HtmlLink(val urlSpan: URLSpan, val spanStart: Int, val spanEnd: Int)
Create spanned html (both formats for test)
val spanned = Html.fromHtml("https://google.com" +
"<br>Google")
Store html
val htmlLinks = ArrayList<HtmlLink>()
spanned.getSpans(0, spanned.length, URLSpan::class.java).forEach { urlSpan ->
htmlLinks.add(HtmlLink(urlSpan,
spanned.getSpanStart(urlSpan),
spanned.getSpanEnd(urlSpan)))
}
Create spannable builder and Linkify it
val builder = SpannableString(spanned)
Linkify.addLinks(builder, Linkify.WEB_URLS)
Restore spans.
htmlLinks.forEach { htmlLink ->
builder.setSpan(URLSpan(htmlLink.urlSpan.url), htmlLink.spanStart, htmlLink.spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
Set finally text
scrollContent.text = builder
Related
I have some amount of informations to be displayed in Dialog Box. It comes like Title, then under it text; Title, then under it text. Like wise, there are 4 titles and 4 descriptions to be displayed. It should come like this
Title One
description;description;description;description;description;description;description;description;description;description;description;description;description;description;description
Title Two
description;description;description;description;description;description;description;description;description;description;description;description;description;description;description
As you can see, there are bold texts, underlined texts, line breaks etc. I want to add this kind of a text to the alert box, so below is what I tried.
TextView msg = new TextView(this);
msg.setText("<html><u>Message</u></html>")
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setTitle("Title");
ab.setView(msg);
ab.setCancelable(false);
//rest of the code
However this trick didn't work. What happened is, all the HTML tags showed up as they are! And the text is not clear! Seems like it mixed with the background of the default colour of AlertBox, black. How can I solve this issue? Please help!
PS: Or am I using the wrong method? Wrong dialog box?
You will need to use Html.fromHtml() to use HTML tags in TextView as:
msg.setText(Html.fromHtml("<u>Message</u>"))
And you also see all HTML tags supported by TextView.
As it turns out, you don't actually need any extra TextViews to do this. Simply include the HTML in your alert's "setMessage()" call (which replaces the "setView()" call in your question) and pass it the html-formatted string. Be sure to only use <b>, <u>, and <i> in your formatting, though because those are the only tags it supports. If you're using a String resource for the text in your alert, call getResources().getText(R.id.yourHtmlString) rather than getResources().getString(R.id.yourHtmlString), though, or the tags will be completely stripped from the String.
If you want to add a link and make it clickable,
msg.setMovementMethod(LinkMovementMethod.getInstance());
msg.setClickable(true);
If you need to add more complex HTML, with CSS and META, you can add a WebView to the dialog, like this:
String webViewString = yourMeta + yourCss + yourHtml;
yourCustomWebView.loadData(webViewString, "text/html; charset=UTF-8",
null);
yourAlertDialog.setView(yourCustomWebView);
This way, you can display fully formatted HTML pages in your dialog.
Try this,
Font color,
String source = "<b><font color=#ff0000> Loading. Please wait..."
+ "</font></b>";
Font underline,
String source = <u>Message</u>
msg.setText(Html.fromHtml(source));
In case if you need it.
Better to use HtmlCompat.fromHtml((htmlString, 0) for compatibility with older versions.
I am trying to format(add styling) to some text using html and setting that as a text for a textview
Spanned text =Html.fromHtml(""+newAllText);
hello.setText(text, TextView.BufferType.SPANNABLE);
But the Html() method returns Spanned string with all the white spaces removed. I have tried using html tags such a <pre> but it didn't help..
It is supposed to be shown nicely like this (the html tags was later removed with the from Html() method) but instead all the white spaces are removed and it looks like this (when it is set as text in the ui it looks like one big continuous paragraph).
Anyone has any clue on this?
Just in case if anyone wants to see the full code:
String SelectedSentence =allText.substring(lastPoint, nextPoint);
String highlighted = "<font color='red'>"+SelectedSentence+"</font>";
StringBuilder newAllText = new StringBuilder(allText);
newAllText.delete(lastPoint, nextPoint+1);
newAllText.insert(lastPoint,highlighted);
newAllText = new StringBuilder("<pre>"+newAllText+"</pre>");
Spanned text =Html.fromHtml(""+newAllText);
hello.setText(text, TextView.BufferType.SPANNABLE);
lastPoint = nextPoint;
Alright, I drop this whole method of HTML text styling and just used SpannableStringBuilder to get the same effect I wanted
highlighted = new SpannableStringBuilder(sb);
highlighted.removeSpan(new BackgroundColorSpan(Color.YELLOW));
highlighted.setSpan(new BackgroundColorSpan(Color.YELLOW),lastPoint, nextPoint, 0);
I try to display an HTML text with its styles, but the text is shown without styling.
Is this normal behavior? It possible?
Is there a nice way to extract the styling from the HTML and apply it to my view?
In my code there are two numbers, one should be red and the other should be striped. In action, they both seems as simple text.
Here is my code:
String str = "<span>  <span dir=\"rtl\" style=\"text-align:right;color:#ff0000;\"> 20.00</span> <span dir=\"rtl\" style=\"text-align:right;text-decoration: line-through;\">26.99 </span></span>";
Spanned spanned = Html.fromHtml(str);
txtView.setText(spanned);
not all the html tags are supported (take a look here)
In my experience I have seen worked only div and p...
I'm developing an android application. I retrieve some data that looks like this:
My Link to Google!</font></b>
I'm applying it to a TextView like this:
myTextView.setText(Html.fromHtml(myHtmlString));
The issue I encounter here is that Html.fromHtml seems to apply a general styling
to any and all links, which is to color them blue and underline them. I'd rather not have it do this, is there any simple solution to make it not stylize links(and therefore, I assume, "font color=whatever" would apply instead)? The behavior does not change if the HTML link tag is on the inside of font/style tags.
Use android:textColorLink attribute. I'm afraid it's the only way to change link color.
If you're sure that you have only one link in the text then you can do the following:
Spanned text = Html.fromHtml(myHtmlString);
ForegroundColorSpan spans[] = text.getSpans(0, text.length(),
ForegroundColorSpan.class);
if (spans.length > 0) {
myTextView.setLinkTextColor(spans[0].getForegroundColor());
}
myTextView.setText(text);
Ok so what i do is the following:
i have a html string i show in a WebView like this:
webView.loadDataWithBaseURL("",htmlText, "text/html","utf-8", null);
i also have a local css file i want to apply to that html String in the webView.
i looked this up for a while but no solution seemed to work.
There should be a way to save the css file in the assets folder and call it from somwhere but i dont have an idea how.
and suggestions?
You can't write anything in the assets folder.
Since you have both the html and the css, I think you can insert css text into the head tag some how like this way
int pos = htmlText.toLowerCase().indexOf("</head>");
if(pos != -1) {
String newHtmlText = htmlText.substring(0, pos) + String.format("<style>%s</style>", cssText) + htmlText.substring(pos + "</head>".length());
webView.loadDataWithBaseURL("",newHtmlText , "text/html","utf-8", null);
}
disclaimer: untested :))
Since i didnt have a nor nor tag i just added them and put the style in the and my html-text in a like this:
String htmlWithCss = "<html><head><style type=\"text/css\">" +css +"</style></head><body>" + htmlText +"</body></html>";
and displayed it in the webView like this:
webView.loadDataWithBaseURL("", htmlWithCss, "text/html","utf-8", null);
This is just to show how to do it when you have blank html-formated text wothout tags around it. i will acceppt J.S. Taylor's answer nevertheless since it showed me basicly what to do.