0

I'm trying to display html code in text view. I want to display this:

Code

I'm using this page to generate this code: http://tohtml.com/java/

HTML:

<pre style='color:#000000;background:#ffffff;'><span style='color:#7f0055; font-weight:bold; '>public</span> <span style='color:#7f0055; font-weight:bold; '>class</span> MainActivity <span style='color:#7f0055; font-weight:bold; '>extends</span> Activity {


     <span style='color:#3f7f59; '>// Called when activity is created</span>
     @Override
     <span style='color:#7f0055; font-weight:bold; '>protected</span> <span style='color:#7f0055; font-weight:bold; '>void</span> onCreate(Bundle savedInstanceState)
     {
         <span style='color:#7f0055; font-weight:bold; '>super</span>.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
</pre>

I'm tried this:

TextView textView; // my text view
String data = loadDataAsString("/sdcard/code.html"); // my function which loads data from file and returning it as String.
textView.setText(Html.fromHTML(data), TextView.BufferType.SPANNABLE);

And i'm getting this as result:

Result

How can I fix it?

I don't want to use WebView.

I'm using API 19 (Android 4.4.4 - KitKat)

4
  • 4
    quick google search said that tags pre and span are not supported ... also i'm pretty sure that style attribute neither
    – Selvin
    Jul 14, 2015 at 13:06
  • @Selvin Is there any solution to make this? Jul 14, 2015 at 13:07
  • 2
    maybe you should use font tag
    – Selvin
    Jul 14, 2015 at 13:09
  • @Selvin Add this as answer and I will vote up and mark as correct. Jul 14, 2015 at 13:11

1 Answer 1

1

Html.fromHtml() supports only a subset of HTML tags. This list is a bit out of date, but it will give you the idea of what you can and cannot use. You would need to alter your HTML to abide by the HTML elements that fromHtml() can work with.

Alternatively:

  • Use a WebView instead of a TextView, or

  • Use a different HTML->Spanned parser, like my SpannableStringGenerator, if it works with HTML that is more to your liking

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.