在使用Android WebView的项目中,富文本有时候会用,因此在此分享一下富文本的简单实现
如何设置相似<html>...</html>
<html> <head></head> <body> 哈哈哈 <a href="http://m.baidu.com/u/10001" class="referer">@每天</a> 我赞你了哦 </body> </html>
方法:
TextView tv = new TextView(context);
tv.setText(Html.fromHtml("<html>...</html>"));
下来看一下富文本的简单实现Demo:
package com.example.textdemo;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str = "<html><head></head><body>哈哈哈 <a href=\"http://m.baidu.com/u/10001\" class=\"referer\">@每天</a>我赞你了哦</body></html>";
// Spanned : 块 (相似<span></span>和<div></div>),将字符串str解析成一个一个的块
Spanned spanned = Html.fromHtml(str);
TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1.setText(spanned);
String content = getBlueText("盖聂, 卫庄, 张良, 天明") + "等 <font color=\"#FF0000\">88人</font>以为很赞";
TextView tv2 = (TextView) findViewById(R.id.tv2);
tv2.setText(Html.fromHtml(content));
}
/**
* 为字符串加蓝色
* @param string
* @return
*/
private String getBlueText(String string) {
return String.format("<font color=\"#0000FF\">%s</font>", string); // string 会替换 %s
}
}
运行效果图以下: