首页 > 代码库 > 32Spannable的使用(Android显示html带图片 (表情开发))
32Spannable的使用(Android显示html带图片 (表情开发))
Android中显示html文件要用Html.fromHtml(...)处理过的返回值,返回值可以成为setText()的参数。只显示带文本的html可以用下面的方法处理html文件。
public static Spanned fromHtml (String source)
显示带图片的html要用下面的方法处理html文件。
public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)<span style="font-family: Simsun;font-size:14px; text-indent: 2em; background-color: rgb(255, 255, 255);">ImageGetter 为处理html中<img>的处理器,生成Drawable对象并返回。</span>
创建ImageGetter 主要实现下面的方法,source为<img>标签中src属性的值。
public Drawable getDrawable(String source)
下例为在TextView和EditView中显示html,并插入图片。
下图只显示html文字,点击按钮会在TextView和EditView文本后添加图片。
代码:
package com.example.test; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Html; import android.text.Html.ImageGetter; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { /** Called when the activity is first created. */ TextView tv; EditText et; Button addPic; String ct; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et=(EditText) this.findViewById(R.id.editText1); tv=(TextView) this.findViewById(R.id.tv); ct="aaa<font color=\"red\">aaa</font>"; addPic=(Button) this.findViewById(R.id.AddPic); addPic.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub ct+="<img src=http://www.mamicode.com/""+R.drawable.ic_launcher+"/"/>";><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" android:orientation="vertical" > <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/AddPic" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
32Spannable的使用(Android显示html带图片 (表情开发))
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。