TextView是我们开发中最常用的组件之一,最常用的功能主要用于文本显示。您可以设置文本大小、颜色和其他效果。如果你认为TextView的功能只是用来显示文本的,那就大错特错了。更多的用途,比如显示图片,实现一些文字点击事件,用链接实现网站和手机号,都可以在TextView中一一实现。坚强点!
项目中经常使用TextView来显示Html格式的文本,所以我今天就简单贴一下。记下来。
main _ test _ html.xml的简单布局,只是一个textview。
-
public class TestActivity extends Activity {private TextView htmlTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_test_html);
/**获得TextView控件*/
htmlTv = (TextView) findViewById(R.id.text);
/**我们自己拼凑Html格式字符串*/
String mHtmlStr = "Html TextView
";
mHtmlStr += "加粗斜体的文字
";
mHtmlStr += "带链接,点击直接跳新浪,呵呵";
/**要使用Html.fromHtml,把含HTML标签的字符串转换成可显示的文本(CharSequence:String,StringBuffer等的父类)样式*/
CharSequence charSequence = Html.fromHtml(mHtmlStr);
// 通过setText给TextView赋值
htmlTv.setText(charSequence);
/**************如果我们要给TextView上添加图片又怎么操作呢***************************************/
/**要用到Html类ImageGetter接口*/
ImageGetter imageGetter = new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int id = Integer.parseInt(source);
Drawable drawable = getResources().getDrawable(id);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
};
/**通过下面的方法就可以显示图片了*/
htmlTv.setText(Html.fromHtml("", imageGetter, null));
}
}
";
mHtmlStr += "带链接,点击直接跳转到新浪,呵呵";
/**要使用Html.fromHtml,请将包含Html标记的字符串转换为可显示的文本(charsequence的父类:string、stringbuffer等。)style */
char sequence char sequence = html . from html(mhtmlstr);
//通过setText
htmltv为TextView赋值。settext(char sequence);
/* * * * * * * *如果我们想在TextView中添加图片怎么办?* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *.image getter image getter = new image getter(){
@ Override
public Drawable getDrawable(String source){
int id = integer . parse int(source);
Drawable Drawable = get resources()。getDrawable(id);
drawable.setBounds(0,0,drawable.getIntrinsicWidth()、drawable . getintrinsicheight());
return drawable;
}
};
/**图片可以通过以下方法显示*/
html TV . settext(html . from html("