public class MainActivity extends Activity {
private TextView tv2;
private TextView tv3;
private TextView tv4;
private TextView tv5;
private TextView tv6;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
tv4 = (TextView) findViewById(R.id.tv4);
tv5 = (TextView) findViewById(R.id.tv5);
tv6 = (TextView) findViewById(R.id.tv6);
setHTML();
setHTML2();
setHTML3();
setHTML4();
}
private void setHTML() {
//若是仅在布局文件中引用,可以把HTML格式字符串写到strings文件中,但要注意,很多很多格式都是不支持的!
//getString(方法)得到的是没有任何格式的字符串,所以若是在代码中设置,就不能把HTML格式字符串写到strings文件中
tv2.setText(Html.fromHtml(getString(R.string.html_str)));
//建议直接在代码中定义并使用。注意双引号要加转义字符
String html = "<html>|<i> 引用 </i>|<font color=\"#aabb00\"> values/ </font>|<font color=\"RED\"> strings </font>|<strong> 中的 </strong>|<em> html </em>|<strike> 格式的 </strike>|<u> 字符串 </u>|<h3> 但是 </h3>|<big> 很多 </big>|<small> 格式 </small>|<b> 都 </b>| <sub> 不 </sub>|<tt> 支持 </tt>|</html>";
tv3.setText(Html.fromHtml(html));
String html2 = "<a href=\"http://www.baidu.com\">代码中支持超链接</a> <font color=\"#aabb00\">支持设置颜色</font>";
tv4.setMovementMethod(LinkMovementMethod.getInstance());
tv4.setText(Html.fromHtml(html2));
}
//显示资源图片
private void setHTML2() {
ImageGetter imageGetter = new ImageGetter() {
public Drawable getDrawable(String source) {
int rId = Integer.parseInt(source);
Drawable drawable = getResources().getDrawable(rId);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
};
String sText = "drawable中的图片:<img src=\"" + R.drawable.ic_launcher + "\" />";
tv5.setText(Html.fromHtml(sText, imageGetter, null));
}
//显示本地图片
private void setHTML3() {
ImageGetter imageGetter = new ImageGetter() {
public Drawable getDrawable(String source) {
Drawable drawable = Drawable.createFromPath(source);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
};
String sText = "本地图片:<img src=\"/mnt/sdcard/temp/1.jpg\" />";
try {
tv6.setText(Html.fromHtml(sText, imageGetter, null));
} catch (Exception e) {
}
}
//显示网路图片
private void setHTML4() {
ImageGetter imgGetter = new Html.ImageGetter() {
public Drawable getDrawable(String source) {
Drawable drawable = null;
URL url;
try {
url = new URL(source);
drawable = Drawable.createFromStream(url.openStream(), "");
} catch (Exception e) {
return null;
}
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
};
//tv7.setText(Html.fromHtml(sText1, imageGetter, null));
}
}