1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 安卓控件使用系列2:TextView实现图文(图片和文字)混排

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

时间:2018-10-06 12:50:30

相关推荐

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

使用TextView实现图文混排是有些开发者并没有实现过,下面来介绍一下如何实现。

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

activity_main.xml文件:

<span style="color:#cc33cc;"> </span> <TextViewandroid:id="@+id/textview"android:layout_width="match_parent"android:layout_height="wrap_content"/>

MainActivity.java文件:

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。