TextView: set Html and own SpannableStringBuilder - android

I have a string that contain html tags. So for set text into TextView I use:
textView.setText(Html.fromHtml(myString));
It's works good.
Also I have own method convertText() with type SpannableStringBuilder. In which method I convert text, where I have something like [text="information"]. I use next for set text:
textView.setText(convertText(myString), TextView.BufferType.SPANNABLE);
For example: myString = "<h1> This is [text="information"]. </h1>"
The result must be:
This is INFORMATION. (with h1 formatted text. caps lock of word information works in method convretText() good)
It's also works good. But how I can use these two setText approach in one time?

Related

How to use Spannable String Builder to enclose string within h1 tag

How can i set a particular string as a title in Edittext. I want to output to look like something like this:
Title
Some other text.
I have tried to make the text bold and give it a larger style. Something like this:
s.setSpan(new StyleSpan(Typeface.BOLD), 0, length ,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
s.setSpan(new RelativeSizeSpan(1.2f), 0, length , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
That does the trick but i wish if i could instead create a h1 tag around the string so the formatted html code i extract from Edittext can be displayed in textview or used elsewhere.
Update
It seems like a problem with Html class. Try something like this.
Log.d("Test", Html.toHtml(Html.fromHtml("<h1>Hello</h1>")));
You would get something like this in your logs:
<p dir="ltr"><b>Hello</b></p>
It seems like Html class is capable of converting h1 tags to spannable but not capable of being able to convert it back to h1 tags.
The fromHtml method converts the header tags to Spannable using a similar trick i already stated above. It's not implemented in the toHtml method and hence it don't create header tags from Spannable. Can someone try to fix this.
You can take a look at HTML.fromHtml(String text)
This will parse HTML and return a spanned string. The only thing notable is, that it's a bit tricky modifying the styles used for the spans.
Try something like this. Which worked for me
SpannableString text = new SpannableString(Html.fromHtml(<h1>Your content</h1>));

Android Charsequence - replacing text

Due to HTML usage within a string resource, I can't convert this to string from a charsequence (I will lose the formatting otherwise).
<string name="exponent_key">x<sup><small>y</small></sup>/string>
After using getString() I want to replace the 'y' with 'other stuff' but how do you do that? It seems like a simple question but for some reason I can't find anything about it.
Edit: Now that I think about it, can I convert the charsequence to a string that contains the HTML code, and then convert it back to a charsequence later?
Edit: Forgot to mention that the string gets set to a button title, and then retrieved (where it is then used).
There is. Create a function where, as a parameter, you take a string that needs to be formatted. And in function, you just take it through itterator, and after that Html.fromHtml()
in your string.xml
<string name="exponent_key">x<sup><small>%1$d</small></sup></string>
in your code
textView.setText(getString(R.string.exponent_key,2))
Let's break down your question in multiple steps:
Replacing the y with "other stuff" can be done like this:
String.format("%1$", "otherStuff");
If you use getString(), you can do the same thing like that:
<string name="exponent_key">%1$</string>
---
String string = getString(R.string.exponent_key, "otherStuff");
For more than one element, do this way:
you can do that like this:
<string name="string_name">%1$ : %2$</string>
---
getString(R.string.string_name, new String[]{"hello", "world"});
In XML you cannot nest HTML code, since HTML is another type of XML and the parser messes up and cannot recognize what tags are for Android and what are for HTML. But.. there's a trick. You can do that in this way:
<string name="exponent_key"><![CDATA[x<sup><small>%1$</small>/sup>]]></string>
So, with the string above in your XML, just use and you're fine:
getString(R.string.exponent_key, "otherStuff");
Note: if you need to show the HTML in a TextView, just use Html.fromHtml:
textView.setText(Html.fromHtml(getString(R.string.exponent_key, "otherStuff")));
Consider the effect you want to achieve.
you can do like this.
SpannableString ss = new SpannableString("2");
// set superscript
ss.setSpan(new SuperscriptSpan(),0,ss.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// set font size
ss.setSpan(new AbsoluteSizeSpan(12,true),0,ss.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.append(ss);

How do I prepend a String to an Android TextView?

There's TextView.append(), but that adds the text to the end of the TextView. I want what I append to go in the beginning (ie, show up on the top of the TextView box).
Have you tried this
textview.setText(" append string" + textView.getText());
Though the spannables will get lost by this method.
If you're concerned about spannables, you can use something like this:
textView.getEditableText().insert(0, "string to prepend");
The getEditableText() returned null to me. Instead, to prepend text to a spannable, I set the text buffertype to SPANNABLE:
in code:
myTextView.setText(myText, TextView.BufferType.SPANNABLE);
or using xml property android:bufferType on your TextView.
Then cast the getText() to Spannable, after which I concat the extra text with existing text:
Spannable currentText = (Spannable) tvTitle.getText();
CharSequence indexedText = TextUtils.concat(String.format("%d. ", index), currentText);
myTextView.setText(indexedText);
As far as I can tell all functions are available from API level 1.
Then use the string you want to append say "hello" to the textview as
textview.setText("hello"+textView.getText())

How to change color of a text using HTML tag in Android

I have a string which contain three words. I want to show the three words in same textview but in different line. For this I have used <br> tag. Now I want to show the last word in red color. I tried so many codes but nothing worked for me.
My code snippet is
viewHolder.cutomerinfo.setText(
customerDetail[0]+Html.fromHtml("<br>")+
customerDetail[1]+Html.fromHtml("<br>")+
Html.fromHtml("<font color='#ff0000'>")+
customerDetail[2]+Html.fromHtml("</font>"));
Do like that:
code:
String toshowstring = customerDetail[0]+customerDetail[1]+
"<font color='red'>"+customerDetail[2]+"</font>";
viewHolder.cutomerinfo.setText(Html.fromHtml(toshowstring));
That's all you want.
^-^
//only one Html.fromHtml() method is enough
viewHolder.cutomerinfo.setText(
customerDetail[0]+Html.fromHtml("<br>"+customerDetail[1]+
"<br><font color='#ff0000'>"+
customerDetail[2]+"</font>"));
for Ref:

Specifying "strikethrough" on a section of TextView text

I have a block of text coming from a webservice, and depending on some tags which I have predefined, I want to style the text before setting it to my TextView. For bold, italics, and underline, I was able to do this easily with the replaceAll command:
PageText = PageText.replaceAll("\\*([a-zA-Z0-9]+)\\*", "<b>$1</b>");
PageText = PageText.replaceAll("=([a-zA-Z0-9]+)=", "<i>$1</i>");
PageText = PageText.replaceAll("_([a-zA-Z0-9]+)_", "<u>$1</u>");
txtPage.setText(Html.fromHtml(PageText), TextView.BufferType.SPANNABLE);
So, to bold a word, surround it with *'s, for italics, surround with _.
But, for strikethrough, Html.fromHtml does not support the "strike" tag, so it can't be done this same way. I've seen examples of using Spannable to set the styling on one section of text, but it requires positional numbers. So, I guess I could loop through the text, searching for - (the tag to represent the strike), then searching for the next one, spanning the text in between, and repeating for all such strings. It will end up being 10 lines of looping code as opposed to 1 for the others, so I'm wondering if there is a more elegant solution out there.
If it is just TextView you can strike through using paint flags
TextView tv=(TextView) v.findViewById(android.R.id.text1);
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
#Suresh solution works if you want to strikethrough the entire TextView but if you want to strikethrough only some portions of the text then use the code below.
tvMRP.setText(text, TextView.BufferType.SPANNABLE);
Spannable spannable = (Spannable) tvMRP.getText();
spannable.setSpan(new StrikethroughSpan(), 3, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Here text is the text which we want out TextView to display, 3 is the no. of characters (starting from 0) from where the strikethrough will start.
You can do it with a custom TagHandler such as the one on this SO question:
Spanned parsed = Html.fromHtml(PageText, null, new MyHtmlTagHandler());
And the TagHandler implements the methods:
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if(tag.equalsIgnoreCase("strike") || tag.equals("s")) {
processStrike(opening, output);
}
}
....
Are you sure Html.fromHtml doesn't support <strike>? It's listed in this Commonsware blog post
It looks like is not really supported, at least it does not work on Android 3.1.
#RMS2 if text is small you can split it into two or three separate text views and apply flag only to the one which you want, not perfect for long texts ;(
Most of the applications we work in are going to use text somewhere throughout the project and thankfully, KTX provides some extension functions when it comes to these parts. For text, we essentially have some functions available for the SpannableStringBuilder class.
For example, after instantiating a Builder instance we can use the build methods to append some bold text:
textView.text =buildSpannedString {
strikeThrough {
append(
value ?: ""
)
}
}

Categories

Resources