根据网上资料,为了方便资料查询,现在开始把一些项目中遇到的问题和比较好的方法进行总结,今天对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中。
第一种是基于该图片不在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中。