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對象,除了可以顯示圖片之外,還可以顯示其他豐富的信息。


1.在TextView類中預定義了一些類似HTML的標簽,通過這些標簽,可以使TextView控件顯示不同的顏色、大小、字體的文字。

<font>:設置顏色和字體                  

<big>:設置大號字                 

<small>:設置小號字

<i>:斜體                 

<b>:粗體                     

<tt>:等寬字體(Monospace)

<br>:換行(行與行之間沒有空行)                

<p>:換行(行與行之間的空行)

<a>:鏈接地址                          

<img>:插入圖像

這些標簽雖然和HTML的標簽類似,但並不具備HTML標簽的全部功能。如<font>標簽只支持color和face兩個屬性。

在使用這些標簽時不能將帶這些標簽的字符串直接賦值到TextView上,而需要使用Html.frmHtml方法將帶標簽的字符串轉換成CharSequence對象,再賦值給TextView。

如果想在顯示的文本中將URL、E-mail、電話等特殊內容高亮顯示,並在單擊時觸發相應的動作(如單擊電話會直接在撥號界面顯示電話號碼),可以設置<TextView>標簽的android:autoLink屬性,該屬性可設置的屬性值如下:

none:不匹配任何鏈接(默認)               web:匹配Web網址                    email:匹配E-mail地址

phone:匹配電話號碼                           map:匹配映射地址                    all:匹配所有的鏈接


下面是示例

  1. public class Main extends Activity {  
  2. @Override  
  3.    public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.main);  
  6.           
  7.         txtFirst=(TextView)findViewById(R.id.txtFirst);  
  8.         
  1.         String html="<font color='red'>樣式一</font> <br>";  
  2.         html+="<font color='#0000FF'> <big> <i> 樣式二 </i> </big> <font>";  
  3.         html+="<font color='@"+android.R.color.white+"'> <tt> <b> <big> <u> 樣式三 </u> </big> </b> </tt> </font> <br>";  
  4.         html+="<big> <a href='http://blog.csdn.net/a_mean'>我的博客:http://blog.csdn.net/a_mean </a> </big>";  
  5.           
  6.         CharSequence charSequence=Html.fromHtml(html);  
  7.         txtFirst.setText(charSequence);  
  8.         //該語句在設置后必加,不然沒有任何效果  
  9.         txtFirst.setMovementMethod(LinkMovementMethod.getInstance());  
  10.           
  11.     }  
  12. }  





2.為指定文字添加背景

有一個很常用的Span類叫BackgroundColorSpan,該類的功能是設置指定字符串的背景色:

第1步:將字符串轉換成SpannableString對象

第2步:確定要設置的子字符串的start和end

第3步:創建BackgroundColorSpan對象

           BackgroundColorSpan bgColorSpan=new BackgroundColorSpan(Color.RED);

第4步:使用setSpan方法將指定子字符串轉換成BackgroundColorSpan對象

            spannableString.setSpan(bgColorSpan,start,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

第5步:用SpannableString對象設置TextView控件

           textView.setText(spannableString);

           textView.setMovementMethod(LinkMovementMethod.getInstance());    


示例如下:

public class MainActivity extends Activity {

private TextView textview1;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

textview1=(TextView) findViewById(R.id.textview1);

String text="heldsafaf";

SpannableString spannableString=new SpannableString(text);

BackgroundColorSpan bgColorSpan=new BackgroundColorSpan(Color.RED);

spannableString.setSpan(bgColorSpan, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

textview1.setText(spannableString);

textview1.setMovementMethod(LinkMovementMethod.getInstance());

}

}


3:帶邊框的TextView

Android SDK本身提供的TextView控件並不支持邊框,所以要想實現這一效果的話我們可以自定義一個控件繼承TextView並修改它,

當然也可以設置TextView控件的背景圖,這個不作演示。

首先定義一個BorderTextView類, extends TextView 。

  1. public class BorderTextView extends TextView {  
  2.   
  3.     public BorderTextView(Context context, AttributeSet attrs) {  
  4.         super(context, attrs);  
  5.     }  
  6.   
  7.     @Override  
  8.     protected void onDraw(Canvas canvas) {  
  9.         super.onDraw(canvas);  
  10.         // 實例化一支畫筆  
  11.         Paint paint = new Paint();  
  12.         // 設置所繪制的邊框顏色為黑色  
  13.         paint.setColor(android.graphics.Color.WHITE);  
  14.         // 繪制上邊框  
  15.         canvas.drawLine(00this.getWidth() - 10, paint);  
  16.         // 繪制左邊框  
  17.         canvas.drawLine(000this.getHeight() - 1, paint);  
  18.         // 繪制右邊框  
  19.         canvas.drawLine(this.getWidth() - 10this.getWidth() - 1,  
  20.                 this.getHeight() - 1, paint);  
  21.         // 繪制上邊框  
  22.         canvas.drawLine(0this.getHeight() - 1this.getWidth() - 1,  
  23.                 this.getHeight() - 1, paint);  
  24.     }  
  25.   
  26. }  

然后在xml布局文件中加入這個控件,這里控件的類型要寫上全名(packageName+className):

<com.hm.BorderTextView
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textColor="#000000" android:layout_margin="20dp"
    android:text="BorderTextView"
    />
效果如下:



4.設置行間距

如果在TextView控件中顯示了多行文本,會有一個默認的行間距。如果要更改這個默認的行間距的話,我們可以使用下面幾種方式:

android:lineSpacingExtra屬性設置精確的行間距。

android:lineSpacingMultiplier屬性設置默認行間距的倍數。

使用Style資源設置行間距。我們需要先在res\values目錄中的文件里定義一個Style:

                  <style name="line_space">
                         <item name="android:lineSpacingMultiplier">1.5</item>
                 </style>

下面是示例。

<?xml version="1.0" encoding="utf-8"?>

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:orientation="vertical" android:layout_width="match_parent"  
  3.     android:layout_height="match_parent">  
  4.     <TextView android:text="第一行\n第二行" android:lineSpacingExtra="20dp"  
  5.         android:id="@+id/textView1" android:layout_width="wrap_content"  
  6.         android:layout_height="wrap_content"></TextView>  
  7.     <TextView android:text="第三行\n第四行"  
  8.         android:lineSpacingMultiplier="1.8" android:id="@+id/textView2"  
  9.         android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>  
  10.     <TextView android:text="第五行\n第六行" style="@style/line_space" android:id="@+id/textView3"  
  11.         android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>  
  12. </LinearLayout>  
此外還可以在代碼中設置:textView.setLineSpacing(50,1.2f);第一個參數是精確值,后一個是倍數。

以上幾種方式,如果同時設置了精銳值和倍數的話,系統會以最大的一個作為行間距的距離。


5.在未顯示完的文本后面加上省略號

當文本內容太多時,TextView控件一屏無法完整顯示,這樣有時候我們就需要在內容中加上省略號。

在TextView標簽中加上android:singleLine="true",這樣內容只會顯示一行,然后再加上android:ellipsize="end",

這樣在該行的末尾就會加上省略號了,android:ellipsize這個屬性值還可以是start,middle,有興趣的朋友可以自己試試。

我們還可以在代碼中進行設置:textView.setEllipsize(TextUtils.TruncateAt.END);后面跟的是一個枚舉類型。


6.走馬燈效果

對於長文本的顯示,除了用省略號之外我們還可以讓它滾動顯示,這樣的效果也叫走馬燈效果。

我們實現這個效果,也要用到上面android:ellipsize的屬性,還有android:marqueeRepeatLimit,和android:focusable屬性。

<TextView android:id="@+id/txtInfo" android:text="這里是測試內容,內容要長容要長要長長長長長長長長長長長長長長長長"
android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever"
android:focusable="true" android:focusableInTouchMode="true"  android:singleLine="true" 
android:layout_width="fill_parent" android:layout_height="wrap_content" />

如果有的朋友實現這個走馬燈效果時發現它跑不起來,記得把android:focusableInTouchMode事件也寫上就行了。




免責聲明!

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



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