您的位置:首页 > 其它

安卓控件使用系列2:TextView实现图文(图片和文字)混排

2015-10-01 19:04 330 查看
使用TextView实现图文混排是有些开发者并没有实现过,下面来介绍一下如何实现。

整体思路:首先定义根据资源文件的变量名返回资源文件ID的方法,定义指向图片资源文件变量名html格式的字符串,写一个通过这个字符串获取资源文件信息的方法返回给字符序列,把这个字符序列绑定到TextView控件。

activity_main.xml文件:

<span style="color:#cc33cc;"> </span> <TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
MainActivity.java文件:

private TextView textView;
//根据资源文件的变量名返回资源文件的文件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;
}

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)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() {

public Drawable getDrawable(String source) {
// TODO Auto-generated method stub
//获得系统资源的信息,比如图片信息
Drawable drawable=getResources().getDrawable(getResourceId(source));
//第三个图片文件按照50%的比例进行压缩
if(source.equals("image1")){
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());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: