Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display HTML text in TextView

I have a string containing HTML. I would like to display the HTML in a TextView control. I found some code and tried it:

def = "some html text"

definition.attributedText = NSAttributedString(
  data: def.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
  options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
      documentAttributes: nil,
      error: nil)

On the option I get an error:

[String: String] is not convertible to string.

Can someone help me display HTML in a TextView?

like image 785
lascoff Avatar asked Aug 13 '15 18:08

lascoff


People also ask

How can I get HTML text in android?

htmlToTextView. setText(HtmlCompat. fromHtml(htmlText, 0)); In the above code we are taking HTML data from fromHtml() and appending to textview using setText() .

Can we use HTML in android?

In Android, we usually need HTML files for displaying the content in WebView. If the developer wants to add any website page or want to create a local webpage for the app then it could be done using HTML files.


1 Answers

This works for me. Remember that the NSAttributedString constructor now throws an NSError object:

Swift 3:

do {
    let str = try NSAttributedString(data: def.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
} catch {
    print(error)
}

Swift 2.x:

do {
    let str = try NSAttributedString(data: def.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
} catch {
    print(error)
}
like image 195
JAL Avatar answered Oct 05 '22 17:10

JAL