zoukankan      html  css  js  c++  java
  • TextView显示html图片方法

        TextVi只可以String的,我们平常用的给setText()方法传递String参数的时候,其实是调用的public final void setText (CharSequence text)方法,String类是CharSequence的子类。而CharSequence子类众多,其中有一个接口Spanned,即类似html的带标记的文本。我们可以用它来在TextView中显示html(自然,有很多html标记是不支持的,只支持一部分)。

        android.text.Html类的一个方法:

    1. public static Spanned fromHtml (String source)  
    2. 在MainActivity类自定义方法:
    public int getResourceId(String name){
            
            try {
                //根据Id的资源名获得Field的对象,使用反射机制来实现的
                Field field = R.drawable.class.getField(name);
                //取回并返回资源id字段(静态变量)的值,使用反射机
                return Integer.parseInt(field.get(null).toString());
            } catch (NoSuchFieldException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            } catch (NumberFormatException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            
            return 0;
        }

    R.java中部分代码:

    1.  public static final class drawable {
              public static final int ic_launcher=0x7f020000;
              public static final int image1=0x7f020001;
              public static final int image2=0x7f020002;
              public static final int image3=0x7f020003;
          }

      在MainActivity类中方法onCreate类中方法部分代码:

    String html = "图像1<img src='image1'/>图像2<img src='image2'/><p>";
            html+="图像3<a href='http://www.baidu.com'><img src='image3'/></a>";
            CharSequence charSequence = Html.fromHtml(html, new ImageGetter() {
                
                public Drawable getDrawable(String source) {  //该方法是每当遇到<imge>标签时,就解析图片,并返回Drawable实例值,该列中解析图片3次,分别为:imag1,
                                        //image2,imag3
    // TODO 自动生成的方法存根 Drawable drawable = getResources().getDrawable(getResourceId(source)); // // Drawable drawable = getResources().getDrawable(R.drawable.image3); if("image3".equals(source)){//等比例将图像缩小百分之五十。 drawable.setBounds(0, 0, drawable.getIntrinsicWidth()/2, drawable.getIntrinsicHeight()/2); }else{ drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); } return drawable; } }, null); textView1.setText(charSequence); textView1.setMovementMethod(LinkMovementMethod.getInstance());
    运行结果如下:
  • 相关阅读:
    竖版文字排列实现《金刚般若波罗蜜心经》
    前端气泡效果实现的方式
    纯CSS绘制三角形
    什么是块级格式上下文
    绝对定位元素left、right、top、bottom值与其margin和宽高的关系
    currentColor在CSS的含义
    HTML/css清除浮动的几种方式
    W3C中不同标准的含义
    table表格标签的属性
    输入你的生日某年某月某日,判断这一天是这一年的第几天、星期几?
  • 原文地址:https://www.cnblogs.com/SoulCode/p/5352712.html
Copyright © 2011-2022 走看看