• 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());
    运行结果如下:
  • 相关阅读:
    LNK2001: unresolved external symbol ... virtual ...
    pygments
    cygwin Mingw
    [转]__attribute__((format (printf, 2, 3))
    [转] C和C++混合编程
    [转]网络包的流转
    [转]程序是如何运行起来的
    [转]Makefile中 .PHONY的作用
    [转]makefile学习
    [转] makefile 中 = := ?= += 区别
  • 原文地址:https://www.cnblogs.com/SoulCode/p/5352712.html
Copyright © 2020-2023  润新知