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事件也写上就行了。



posted @ 2015-08-25 18:50  xiexie2015  阅读(19705)  评论(0编辑  收藏  举报