In the project development process, you need to put the html content in strings. xml file, and then read it to TextView. I thought that SetText would be the same as plain text, and the result would not work much better than I expected. after searching on the internet, find some methods and organize them by yourself. Record them here and attach your own test project. first paste strings. key Content in the xml file:
<string name="msg1"> <b>Hello world!</b><br/> <a href="http://blog.csdn.net/Banket004">link</a> </string> <string name="msg2"> <![CDATA[ <b>Hello world!</b><br/> <a href="http://blog.csdn.net/Banket004">link</a> ]]> </string>
Method 1: adding the getText method of Context to a common html string can process tags common to html and xml, but cannot correctly parse tags not found in xml such as "<br/>. some tags are easy to be ignored. In fact, html tags are implemented using xml tags. You can only use getText of Context to obtain html text in the format. If you use getString of Context, html text format tags are automatically filtered out. this method does not require Html classes. some code is as follows:
TextView view1 = (TextView)findViewById(R.id.textView1); TextView view2 = (TextView)findViewById(R.id.textView2); TextView view3 = (TextView)findViewById(R.id.textView3); TextView view4 = (TextView)findViewById(R.id.textView4); TextView view5 = (TextView)findViewById(R.id.textView5); TextView view6 = (TextView)findViewById(R.id.textView6); TextView view7 = (TextView)findViewById(R.id.textView7); TextView view8 = (TextView)findViewById(R.id.textView8); view1.setText(getString(R.string.msg1)); view2.setText(getText(R.string.msg1)); view3.setText(Html.fromHtml(getString(R.string.msg1))); view4.setText(Html.fromHtml(getText(R.string.msg1).toString()));
Method 2: Add getString (or getText) of Context to the specially processed html string ). this method requires strings. process the corresponding string in the xml file, and add "<! [CDATA [", add"] "to the end of the html content. You can use the getString (or getText) method of Context to obtain the content, then, use the fromHtml method of Html to obtain the Spanned corresponding to the html content, and call the SetText of TextView. some code is as follows:
view5.setText(getString(R.string.msg2)); view6.setText(getText(R.string.msg2)); view7.setText(Html.fromHtml(getString(R.string.msg2))); view8.setText(Html.fromHtml(getText(R.string.msg2).toString()));