android textview組件顯示富文本信息


android 中textview顯示富文本信息具有以下幾種方式:

1,利用富文本標簽,類似於html標簽,如<b>,<font>,<img>等,不過不能直接作為textview.setText的參數值,而應該靜html.fromHtml方法將這些文本轉換為charsequence對象。如果想要顯示圖片的時候,還需要實現imagegetter接口

2,重寫ondraw方法

3,利用webview組件顯示html頁面

4,textview中顯示圖片還可以使用imagespan對象,該對象用來封裝bitmap對象,並通過spannableString對象封裝imagespan對象,將其作為settext方法的參數。

方法1的代碼如下:

TextView tv = (TextView) this.findViewById(R.id.tv);
        String html="<strong>我的測試</strong><img src=\"ic_launcher-web.png\"><img src=\"\">";
        CharSequence charSequence=Html.fromHtml(html,new ImageGetter(){
            
            @Override
            public Drawable getDrawable(String arg0) {
                 Drawable drawable=MainActivity.this.getResources().getDrawable(R.drawable.ic_launcher);
                 //下面這句話不可缺少
                 drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
                return drawable;
            }},null);
    tv.setText(charSequence);    
    }

其中碰到img標簽返回的drawable對象是由接口返回的值來決定,如果得到的是網絡上的圖像,那么顯示的就是網絡的圖像。

    TextView tv = (TextView) this.findViewById(R.id.tv);
        String html="<strong>我的測試</strong><img src=\"http://tp1.sinaimg.cn/2668435432/180/5636292734/0\">";
        CharSequence charSequence=Html.fromHtml(html,new ImageGetter(){
    
            @Override
            public Drawable getDrawable(String arg0) {
                   Drawable d = null;
                   try {
                       InputStream is = new DefaultHttpClient().execute(new HttpGet(arg0)).getEntity().getContent();
                       Bitmap bm = BitmapFactory.decodeStream(is);
                       d = new BitmapDrawable(bm);
                       d.setBounds(0, 0, 200, 300);

                   } catch (Exception e) {e.printStackTrace();}

                   return d;
              }
            },null);
    tv.setText(charSequence);    

 

利用這種方法更多的是顯示從網絡上獲取的照片(另外一種更廣泛的方法是利用webview);如果需要顯示的是本地資源文件的圖像資源,更多的利用imagespan。

TextView tv = (TextView) this.findViewById(R.id.tv);
        Drawable drawable=getResources().getDrawable(R.drawable.ic_launcher);
        drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
        ImageSpan span=new ImageSpan(drawable);
        SpannableString spannableString=new SpannableString("span");
        spannableString.setSpan(span, 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv.setText(spannableString);
            //用超鏈接標記文本
            spannableString.setSpan(new URLSpan("tel:4155551212"), 2, 3,  
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
           
     
    }

可見利用span對象,除了可以顯示圖片之外,還可以顯示其他豐富的信息。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM