Byron's log
‹‹ back
android TextView HTML富文本应用
Create Time : 2011-06-23 17:26:27
Modify Time : 2011-06-23 17:41:23

autoLink

autoLink是可应用于静态布局的一个属性,它可自动转化url、email、phone等文本信息。通常,这个方法只能解决一些式样上的要求(看着舒服) autoLink的官方说明 Controls whether links such as urls and email addresses are automatically found and converted to clickable links. The default value is "none", disabling this feature. Must be one or more (separated by '|') of the following constant values. autoLink的属性表
ConstantValueDescription
none0x00 Match no patterns (default).
web0x01 Match Web URLs.
email0x02 Match email addresses.
phone0x04 Match phone numbers.
map0x08 Match map addresses.
all0x0f Match all patterns (equivalent to web|email|phone|map).

android.text.Html

当你的TextView里加载了相当多的html标签的话,使用android.text.Html才是解决之道,因为通常TextView不是独立显示,比较在listView中,TextView只是一个item,而item本身是有click事件的,这会让TextView中的链接失效。解决办法?
TextView txtContent = (TextView) view.findViewById(R.id.update_content);
txtContent.setMovementMethod(LinkMovementMethod.getInstance());
txtContent.setText(android.text.Html.fromHtml(data.get(position).get("content").toString()));

关于TextView显示图片

这里需要说明一下android.text.Html.fromHtml有一个重载方法,这个重载方法就是为了解决图片显示的问题。为什么图片显示会有问题?因为TextView有一种需求,就是将信息以html标签方式显示,但并不是来自于网络。所以img标签要如何加载? public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler) 在原型中看到的,通常重点在于imageGetter的抽象方法的实现。
ImageGetter imgGetter = new ImageGetter() { 
	public Drawable getDrawable(String source) {
                Drawable drawable = null;
		try{
			drawable = Drawable.createFromStream((new URL(source)).openStream(),"tmp.jpg");
		}catch(Exception e){
			e.printStackTrace();
		}
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                return drawable;
	}
};
通过Stream重新加载图片(一般用于网络直接下载显示) drawable = Drawable.createFromStream((new URL(source)).openStream(),"tmp.jpg"); 通过Path重新加载图片(一般用于手机本地加载图片) drawable = Drawable.createFromPath(uri);