安卓控件使用系列2:TextView实现图文(图片和文字)混排
2015-10-01 19:04
330 查看
使用TextView实现图文混排是有些开发者并没有实现过,下面来介绍一下如何实现。
整体思路:首先定义根据资源文件的变量名返回资源文件ID的方法,定义指向图片资源文件变量名html格式的字符串,写一个通过这个字符串获取资源文件信息的方法返回给字符序列,把这个字符序列绑定到TextView控件。
activity_main.xml文件:
整体思路:首先定义根据资源文件的变量名返回资源文件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()); }
相关文章推荐
- Trie树的java实现
- spring MVC访问静态文件,如jpg,js,css
- zoj 3430(ac自动机)
- 第一篇博客
- 《京东技术解密》读后感
- C++ | 数组与指针
- Graphite数据清除与查看
- LightOJ 1220 Mysterious Bacteria
- for JDK1.5 OR HIGHER
- Spring MVC静态资源处理
- 习题6-11 树重建 UVa 10410 *
- Python连接mysql数据库
- CodeForces 2A Winner(CodeForces的题意总是那么难理解)——Codeforces Beta Round #2
- 递归求解数组的和 Java实现
- 数组中只出现一次的数字(剑指offer)思维有点巧
- Android系统自带分享功能的实现(可同时分享文字和图片)
- 2015弱校联盟(1) - E. Rectangle
- 2015弱校联盟(1) - E. Rectangle
- vs开发调用窗体的方法
- RBAC用户角色权限设计方案