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());
    运行结果如下:
  • 相关阅读:
    【持续更新】leetcode算法-数组篇
    【转】敏捷开发之Scrum扫盲篇
    设计Twitter的api
    给一个表达式字符串加括号,计算它的所有的可能的值
    判断一个整数是否是平方数
    Spring Cloud 入门教程(七): 熔断机制 -- 断路器
    断路器(Curcuit Breaker)模式
    Spring Cloud 入门教程(六): 用声明式REST客户端Feign调用远端HTTP服务
    Spring Cloud 入门教程(五): Ribbon实现客户端的负载均衡
    Spring Cloud 入门教程(四): 分布式环境下自动发现配置服务
  • 原文地址:https://www.cnblogs.com/SoulCode/p/5352712.html
Copyright © 2011-2022 走看看