In an app, instead of using a textview, we can use a webview. Why? Because webview is better looking. And, more importantly, we can format the text easily - specifically for long, long text. And, yes, it has an automatic scroll controls.
Now how do we display a static text in a webview?
String str="your text here";
webview.loadData(str,"text/html",null);
But your string should also have html tags in them. The simplest tags are html and body. So surround your string with these.
String str="your text here";
String str = "<html><body>"+str+"</body>";
webview.loadData(str,"text/html",null);
But if you are using for formatting the text, like bold, italic, different font etc. to be used for some parts of the text? How do you get that done?
The straight forward solution is learn html and hand code all the B 's and slash B's etc. yourself.
Of course, I am kidding. There are plenty of html editors available for automating this task. Look for a editor with WYSWIG feature. And take your text, format them using tool bar buttons and get the source html code, and paste it. I am currently using Kompozer.
OK. That task is completed. Now your webview is looking all cool and nice. But for any reason, if you want to extract plain text from this string, how do you accomplish that? You need to remove all the html tags.
Thankfully there is one line solution for this
Now how do we display a static text in a webview?
String str="your text here";
webview.loadData(str,"text/html",null);
But your string should also have html tags in them. The simplest tags are html and body. So surround your string with these.
String str="your text here";
String str = "<html><body>"+str+"</body>";
webview.loadData(str,"text/html",null);
But if you are using for formatting the text, like bold, italic, different font etc. to be used for some parts of the text? How do you get that done?
The straight forward solution is learn html and hand code all the B 's and slash B's etc. yourself.
Of course, I am kidding. There are plenty of html editors available for automating this task. Look for a editor with WYSWIG feature. And take your text, format them using tool bar buttons and get the source html code, and paste it. I am currently using Kompozer.
OK. That task is completed. Now your webview is looking all cool and nice. But for any reason, if you want to extract plain text from this string, how do you accomplish that? You need to remove all the html tags.
Thankfully there is one line solution for this
String plainText = android.text.Html.fromHtml(strWithAllTags).toString();
This will remove all html tags from the string and give you the content.
Note: I formatted using HTML tags - but not only did my courier font did not show correctly, where ever I used a different font, there was an extra line in between. So if you face such problem, you need to use loadDataWithBaseURL as shown below.
wv.loadDataWithBaseURL(null,str,"text/html", null,null);
Comments
Post a Comment