图文混排,文字就不说了,主要是显示图片的方法
1、TextView使用ImageSpan显示图片
- <span style="font-size:18px;">ImageSpan span = new ImageSpan(this, R.drawable.ic_launcher);//加载图片的资源
- SpannableString spanStr = new SpannableString("http://orgcent.com");//不想要这个字符串可以试试空字符串
- spanStr.setSpan(span, spanStr.length()-1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
- mTVText.setText(spanStr);//完成添加</span>
2.使用Html类进行添加,可达到如图效果,本方法主要是使用html标签的操作,所有内容可以很丰富,其他用途可自查sdk文档
完整源码:TextView图文混排
- <span style="font-size:18px;">public int getResourceId(String name) {
- try {
- // 根据资源的ID的变量名获得Field的对象,使用反射机制来实现的
- Field field = R.drawable.class.getField(name);
- // 取得并返回资源的id的字段(静态变量)的值,使用反射机制
- return Integer.parseInt(field.get(null).toString());
- } catch (Exception e) {
- // TODO: handle exception
- }
- return 0;
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- TextView textView = (TextView) this.findViewById(R.id.textview);
- textView.setTextColor(Color.BLACK);
- textView.setBackgroundColor(Color.WHITE);
- textView.setTextSize(20);// 设置字体的大小
- String html = "图像1<img src='image1'/>图像2<img src='image2'/>图像3<img src='image3'/><p>";
- html += "图像4<a href='http://www.baidu.com'><img src='image4'></a>图像5<img src='image5'/>";
- CharSequence charSequence = Html.fromHtml(html, new ImageGetter() {
- @Override
- public Drawable getDrawable(String source) {
- // TODO Auto-generated method stub
- // 获得系统资源的信息,比如图片信息
- Drawable drawable = getResources().getDrawable(
- getResourceId(source));
- // 第三个图片文件按照50%的比例进行压缩
- if (source.equals("image3")) {
- drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 2,
- drawable.getIntrinsicHeight() / 2);
- } else {
- drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
- drawable.getIntrinsicHeight());
- }
- return drawable;
- }
- }, null);
- textView.setText(charSequence);
- textView.setMovementMethod(LinkMovementMethod.getInstance());</span>
Html类可以将一些常用的html标签进行格式化显示
3、在TextView四周显示图片
- <span style="font-size:18px;">mTVText.setText("setCompoundDrawables");//添加文字
- Drawable d = getResources().getDrawable(R.drawable.ic_launcher);//获取图片资源
- d.setBounds(0, 0, 50, 50); //必须设置图片大小,否则不显示
- mTVText.setCompoundDrawables(d , null, null, null);设置图片显示的位置(上下左右),此方法的不同之处</span>