TextView实现图文混合编排
一、简介
在这里实现图文混合编排使用的是:TextView中预定义的类似Html的标签
二、方法
* 1、设置好html标签的文本
String html="<font>图片1</font><img src='image1'/>";
html+="<font>图片2</font><img src='image2'/>";
html+="<font>图片3</font><img src='image3'/>";
html+="<font>图片4</font><img src='image4'/>";
html+="<font>图片5</font><img src='image5'/>";
* 2、为之前的文本声明Html.fromHtml,方便TextView解析为html标签
tv_one.setText(Html.fromHtml(text1));
因为有图片,我们要获取图片源,所以上面的那句不行;
所以如下:
CharSequence text=Html.fromHtml(html, new ImageGetter() {中间省略}, null);
new ImageGetter() {中间省略}这部分比较复杂,看实例代码吧,实质就是取到R文件中图片对应的ID
* 3、将CharSequence字符串序列的文本text插入到TextView控件中即可
tv_textAndImage.setText(text);
这里是charSequence是因为Html.fromHtml方法的返回值是类型,
看下下面的类图特别好懂:
三、代码实例
效果图
代码
fry.ActivityDemo2
1 package fry;
2
3 import java.lang.reflect.Field;
4
5 import com.example.textViewDemo1.R;
6
7 import android.app.Activity;
8 import android.graphics.drawable.Drawable;
9 import android.os.Bundle;
10 import android.text.Html;
11 import android.text.Html.ImageGetter;
12 import android.widget.TextView;
13
14 public class ActivityDemo2 extends Activity{
15 private TextView tv_textAndImage;
16 @Override
17 protected void onCreate(Bundle savedInstanceState) {
18 // TODO Auto-generated method stub
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.activity02);
21 setTitle("TextViewDemo2");
22 tv_textAndImage=(TextView) findViewById(R.id.tv_textAndImage);
23 //第一步,设置文本
24 String html="<font>图片1</font><img src='image1'/>";
25 html+="<font>图片2</font><img src='image2'/>";
26 html+="<font>图片3</font><img src='image3'/>";
27 html+="<font>图片4</font><img src='image4'/>";
28 html+="<font>图片5</font><img src='image5'/>";
29 //第二步,告诉TextView控件这是html,并且获取文本中的图片源
30 CharSequence text=Html.fromHtml(html, new ImageGetter() {
31
32 public Drawable getDrawable(String source) {
33 // TODO Auto-generated method stub
34 //根据图片资源ID获取图片
35 //getResources就是去找项目里面的res文件夹
36 Drawable drawable=getResources().getDrawable(getDrawableResurceID(source));
37 //一定要加上边界这部分代码。要不然drawable会因为信息不完整读不出来图片
38 //分别是left top width height
39 drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
40 return drawable;
41 }
42 }, null);
43 //第三步、将CharSequence字符串序列的文本text插入到TextView控件中即可
44 tv_textAndImage.setText(text);
45
46 }
47 /**
48 * 获取图片的资源ID
49 * @param imageName 图片的名称
50 * @return 图片对应的ID
51 *
52 */
53 private int getDrawableResurceID(String imageName){
54 //利用反射机制取得图片的id
55 /*
56 * 其实是找com.example.textViewDemo1.R.drawable.image1的值,也就是
57 * public static final int image1=0x7f020001;
58 * 也就是0x7f020001
59 * 例如image1,返回的就是0x7f020001
60 */
61 try {
62 Field field=R.drawable.class.getField(imageName);
63 return Integer.parseInt(field.get(null).toString());
64 } catch (Exception e) {
65 // TODO Auto-generated catch block
66 e.printStackTrace();
67 }
68
69