Retaining whitespaces in textview in android - java

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

Related

Using HTML in Android Alert Dialog

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.

Using Linkify.addLinks combine with Html.fromHtml

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

Set text above image in TextView using HTML

I have a list of Strings that I add to TextViews one by one. The text is html so I can add images within the text.
So my question is... How can I add an Image so that the text appears above it. currently while using HTML.ImageGetter class text is added below the image, not above it:
Here is my Html text to be shown:
myText += "<img src='titles.png'><span> text to be above image </span>";
Please try following code as example(Html text is changed):
myText += "<div style='position: relative;width: 100%;'> <img src='titles.png'><span style='position: absolute;top: 100px;left: 0;width: 100%;'> text to be above image </span></div>";
I referred http://css-tricks.com/text-blocks-over-image/ for checking for css properties.
Hope this is helpful for you.
Thanks & Regards,
Chanchal
you can add a simple alt="texthover" to the anchor tag and it will display the text in the alt in most browsers.
But that is not as good as creating an a.hover class that would display text or a div that has text.
Does that help?

TextView doesn't apply HTML styles using Html.fromHtml

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>&nbsp <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...

Change style of html links in TextViews after executing Html.fromHtml

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

Categories

Resources