android TextView呈现图片方式

根据网上资料,为了方便资料查询,现在开始把一些项目中遇到的问题和比较好的方法进行总结,今天对TextView呈现图片方式提供2种方法
第一种是基于该图片不在drawable下面,只提供路径的方式,如相册中的,网络中的等
/**
* 通过textview显示
* @author ljl
* @createtime Dec 5, 2012 3:53:06 PM
* @param htmlString
* @return
*/
public CharSequence formatString(String htmlString) {

CharSequence ch = Html.fromHtml(htmlString, new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable drawable = Drawable.createFromPath(source);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
return drawable;
}
}, null);

return ch;
}

调用方式:
后面就可以TextView.setText(formatString("<img src='"+file.getPath()+"' />"));
第二种方式,该图片在drawable下面
public CharSequence formatString(String htmlString) {

CharSequence ch = Html.fromHtml(htmlString, new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
// TODO Auto-generated method stub
Drawable drawable = getResources().getDrawable(getResourceId(source));
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
return drawable;
}
}, null);

return ch;
}
// 利用反射机制,通过资源名字得到资源的ID
public int getResourceId(String name) {
try {
Field field = R.drawable.class.getField(name);
return Integer.parseInt(field.get(null).toString());
} catch (Exception e) {
// TODO: handle exception
}
return 0;
}

调用方式:TextView.setText(formatString("<img src='aaa' />"));
其中aaa就是代表R文件中的应用id名字,该方式的方法需要写在activity中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值