android基础-TextView详解

来源:互联网 发布:淘宝组织架构 编辑:程序博客网 时间:2024/06/06 03:36
TextView用于显示文本,该类继承于View。

1.TextView属性详解

android:autoLink :设置是否当文本为URL链接/email/电话号码/map时,文本显示为可点击的链接。可选值(none/web /email/phone/map/all)
android:autoText :如果设置,将自动执行输入值的拼写纠正。此处无效果,在显示输入法并输入的时候起作用。
android:bufferType : 指定getText()方式取得的文本类别。选项editable 类似于StringBuilder :可追加字符,也就是说getText后可调用append方法设置文本内容。spannable :则可在给定的字符区域使用样式,参见这里1、这里2。
android:capitalize :设置英文字母大写类型。此处无效果,需要弹出输入法才能看得到,参见EditView此属性说明。
android:cursorVisible:设定光标为显示/隐藏,默认显示。
android:digits:设置允许输入哪些字符。如“1234567890.+-*/% ()”
android:drawableBottom:在text的下方输出一个drawable,如图片。如果指定一个颜色的话会把text的背景设为该颜色,并且同时和background使用时覆盖后者。
android:drawableLeft:在text的左边输出一个drawable,如图片。
android:drawablePadding:设置text与drawable(图片)的间隔,与drawableLeft、 drawableRight、drawableTop、drawableBottom一起使用,可设置为负数,单独使用没有效果。
android:drawableRight:在text的右边输出一个drawable。
android:drawableTop:在text的正上方输出一个drawable。
android:editable:设置是否可编辑。
android:editorExtras:设置文本的额外的输入数据。
android:ellipsize:设置当文字过长时,该控件该如何显示。有如下值设置:”start”—?省略号显示在开头;”end” ——省略号显示在结尾;”middle”—-省略号显示在中间;”marquee” ——以跑马灯的方式显示(动画横向移动)。
android:freezesText:设置保存文本的内容以及光标的位置。
android:gravity:设置文本位置,如设置成“center”,文本将居中显示。
android:hintText:为空时显示的文字提示信息,可通过textColorHint设置提示信息的颜色。此属性在 EditView中使用,但是这里也可以用。
android:imeOptions:附加功能,设置右下角IME动作与编辑框相关的动作,如actionDone右下角将显示一个“完成”,而不设置默认是一个回车符号。这个在EditView中再详细说明,此处无用。
android:imeActionId:设置IME动作ID。
android:imeActionLabel:设置IME动作标签。
android:includeFontPadding:设置文本是否包含顶部和底部额外空白,默认为true。
android:inputMethod:为文本指定输入法,需要完全限定名(完整的包名)。例如:com.google.android.inputmethod.pinyin,但是这里报错找不到。
android:inputType:设置文本的类型,用于帮助输入法显示合适的键盘类型。在EditView中再详细说明,这里无效果。
android:linksClickable:设置链接是否点击连接,即使设置了autoLink。
android:marqueeRepeatLimit:在ellipsize指定marquee的情况下,设置重复滚动的次数,当设置为 marquee_forever时表示无限次。
android:ems:设置TextView的宽度为N个字符的宽度。这里测试为一个汉字字符宽度
android:maxEms:设置TextView的宽度为最长为N个字符的宽度。与ems同时使用时覆盖ems选项。
android:minEms:设置TextView的宽度为最短为N个字符的宽度。与ems同时使用时覆盖ems选项。
android:maxLength:限制显示的文本长度,超出部分不显示。
android:lines:设置文本的行数,设置两行就显示两行,即使第二行没有数据。
android:maxLines:设置文本的最大显示行数,与width或者layout_width结合使用,超出部分自动换行,超出行数将不显示。
android:minLines:设置文本的最小行数,与lines类似。
android:lineSpacingExtra:设置行间距,需要带单位dip/px等。
android:lineSpacingMultiplier:设置行间距的倍数。如”1.2”
android:numeric:如果被设置,该TextView有一个数字输入法。此处无用,设置后唯一效果是TextView有点击效果,此属性在EdtiView将详细说明。
android:password:以小点”.”显示文本
android:phoneNumber:设置为电话号码的输入方式。
android:privateImeOptions:设置输入法选项,此处无用,在EditText将进一步讨论。
android:scrollHorizontally:设置文本超出TextView的宽度的情况下,是否出现横拉条。
android:selectAllOnFocus:如果文本是可选择的,让他获取焦点而不是将光标移动为文本的开始位置或者末尾位置。 TextView中设置后无效果。
android:shadowColor:指定文本阴影的颜色,需要与shadowRadius一起使用。
android:shadowDx:设置阴影横向坐标开始位置。
android:shadowDy:设置阴影纵向坐标开始位置。
android:shadowRadius:设置阴影的半径。设置为0.1就变成字体的颜色了,一般设置为3.0的效果比较好。
android:singleLine:设置单行显示。如果和layout_width一起使用,当文本不能全部显示时,后面用“…”来表示。如果不设置singleLine或者设置为false,文本将自动换行。
android:text:设置显示文本。
android:textAppearance:设置文字外观。如 “?android:attr/textAppearanceLargeInverse”这里引用的是系统自带的一个外观,?表示系统是否有这种外观,否则使用默认的外观。可设置的值如下:textAppearanceButton/textAppearanceInverse/textAppearanceLarge/textAppearanceLargeInverse/textAppearanceMedium/textAppearanceMediumInverse/textAppearanceSmall/textAppearanceSmallInverse
android:textColor:设置文本颜色
android:textColorHighlight:被选中文字的底色,默认为蓝色
android:textColorHint:设置提示信息文字的颜色,默认为灰色。与hint一起使用。
android:textColorLink:文字链接的颜色.
android:textScaleX:设置文字之间间隔,默认为1.0f。
android:textSize:设置文字大小,推荐度量单位”sp”,如”15sp”
android:textStyle:设置字形[bold(粗体) 0, italic(斜体) 1, bolditalic(又粗又斜) 2] 可以设置一个或多个,用“|”隔开
android:typeface:设置文本字体,必须是以下常量值之一:normal 0, sans 1, serif 2, monospace(等宽字体) 3]
android:height:设置文本区域的高度,支持度量单位:px(像素)/dp/sp/in/mm(毫米)
android:maxHeight:设置文本区域的最大高度
android:minHeight:设置文本区域的最小高度
android:width:设置文本区域的宽度,支持度量单位:px(像素)/dp/sp/in/mm(毫米),与layout_width 的区别看这里。
android:maxWidth:设置文本区域的最大宽度
android:minWidth:设置文本区域的最小宽度

2.TextView设置不同颜色、字体、大小、超链接、可点击、添加图片等效果

第一种方式:通过Html类的fromHtml(String info)方法,引用Html标签<font></font>等标签中的文字。例如:

   String newMessageInfo = "<font color='red'><b>红色内容</b></font>TextView学习显示不同颜色";
   mTextView.setTextView(Html.fromHtml(newMessageInfo));

  Html类:在进行Android开发中经常回忽略Html类。这个类其实很简单,就是将HTML标签文本解析成普通的样式文本。
  该有四个常用方法:
  •  public static String escapeHtml (CharSequence text):从给定的代表性名文中返回 Html 转义字符。
  •  public static Spanned fromHtml (String source):从 Html 字符串中返回可显示的样式文本。
  •  public static Spanned fromHtml (String source,Html.ImageGetter imageGetter,Html.TagHandler tagHandler):Html 字符串     中返回可显示的样式文本。
        参数说明:
        source:包含Html的字符串。
    imageGetter:imageGetter对象(接口),处理html中的图片标签。当系统解析到<img>标签时就会调用imageGetter对象的getDrawable方法,并将src
    属性值传递传入getDrawable方法。至于src属性的具体含义,就要在getDrawable方法中确定了。getDrawable方法返回一个Drawable对象。我们可 
    以res/drawable资源、assets资源、SD卡以及网络上获得图像资源,并封装成Drawable对象,另外,需要调用Drawable的setBounds()方法,设置图 
    片显示的位置和大小。
    tagHandler:TagHandler对象。系统每处理一个标签时都会调用该对象的handleTag方法(在这里面可以处理自定义的标签)。不过这个参数并不常用。如果不用可以设为null。
  • public static String toHtml (Spanned text):将文本转换成 Html。
  实例如下:
  布局文件:
  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/container"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.htt.main.MainActivity"
          tools:ignore="MergeRootFrame" >
         <TextView
             android:id="@+id/tv_text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textScaleX="1.2"
            android:lineSpacingExtra="2dip"
            android:textSize="14.0sp"
            android:linksClickable="true"
            android:autoLink="all"/>
        </FrameLayout>

    Activity代码:
    public class MainActivity extends ActionBarActivity {
    private TextView tv_text;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
        tv_text=(TextView)this.findViewById(R.id.tv_text);
        String htmlInfo="<font color='red'><b>红色内容</b></font>"+
                        "<font color='green'><b>绿色内容</b></font>"+
               "<a href=www.baidu.com>百度链接</a>"+
                        "<img width='50px',height='50px'></img>"+
               "<strike>Hello,World</strike>"+
               "TextView学习显示不同颜色\n"+
              "www.baidu.com";
        setFormatText(htmlInfo,tv_text);
  }

private void setFormatText(String html,TextView text_view){
if(!html.contains("</img>")){
text_view.setText(Html.fromHtml(html));
}else{
text_view.setText(Html.fromHtml(html, new ImageGetter() {
@Override
public Drawable getDrawable(String soure) {//soure代表图片路径
// TODO Auto-generated method stub
Drawable d=MainActivity.this.getResources().getDrawable(R.drawable.ic_launcher);
   d.setBounds(1, 1, 100, 100);
return d;
}
}, new CustomeHtmlTagHandler()));
}
}

/**
* @author HTT
*处理自定义标签<strike>,设定该标签中的文字加上横线
*/
public class CustomeHtmlTagHandler implements TagHandler {
      public void handleTag(boolean opening, String tag, Editable output,
               XMLReader xmlReader) {
           if(tag.equalsIgnoreCase("strike") || tag.equals("s")) {
               processStrike(opening, output);
           }
       }
      
       private void processStrike(boolean opening, Editable output) {
           int len = output.length();
           if(opening) {
               output.setSpan(new StrikethroughSpan(), len, len, Spannable.SPAN_MARK_MARK);
           } else {
               Object obj = getLast(output, StrikethroughSpan.class);
               int where = output.getSpanStart(obj);
               output.removeSpan(obj);
               if (where != len) {
                   output.setSpan(new StrikethroughSpan(), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
               }
           }
       }

       private Object getLast(Editable text, Class kind) {
           Object[] objs = text.getSpans(0, text.length(), kind);
           if (objs.length == 0) {
               return null;
           } else {
               for(int i = objs.length;i>0;i--) {
                   if(text.getSpanFlags(objs[i-1]) == Spannable.SPAN_MARK_MARK) {
                       return objs[i-1];
                   }
               }
               return null;
           }
       }
    }
   }
  
 在该实例中,用到了几个类,以下对该类进行说明:
 Spanned接口:该接口实现了一些用于标记或编辑文本的一些方法。比如标记或编辑文本中的某些指定的文字。并不是所有的文本类都能被标记或编辑。只有那些实现该接口的文本对象才可以。Spannable接口和Editable接口继承了该接口,该接口有以下方法:
    • Methods Modifier and TypeMethod and DescriptionintgetSpanEnd(Object tag)
      Return the end of the range of text to which the specified markup object is attached, or -1 if the object is not attached.
      intgetSpanFlags(Object tag)
      Return the flags that were specified when Spannable.setSpan(java.lang.Object, int, int, int) was used to attach the specified markup object, or 0 if the specified object has not been attached.
      <T> T[]getSpans(int start, int end, Class<T> type)
      Return an array of the markup objects attached to the specified slice of this CharSequence and whose type is the specified type or a subclass of it.
      intgetSpanStart(Object tag)
      Return the beginning of the range of text to which the specified markup object is attached, or -1 if the object is not attached.
      intnextSpanTransition(int start, int limit, Class type)
      Return the first offset greater than or equal to start where a markup object of class type begins or ends, or limit if there are no starts or ends greater than or equal to start but less than limit.
另外,该接口还有一些标记常量。

Spannable接口:该接口用于实现标记及编辑文本中某些文本的属性。比如:让文本中的指定文字可点击、在文本中显示图片等。该接口方法有:
    • Methods Modifier and TypeMethod and DescriptionvoidremoveSpan(Object what)
      Remove the specified object from the range of text to which it was attached, if any.
      voidsetSpan(Object what, int start, int end, int flags)
      Attach the specified markup object to the range start…end of the text, or move the object to that range if it was already attached elsewhere.
Editable接口:该接口用于实现动态改动文本中显示的内容。可以向显示的文本中的具体位置添加文字或删除文字等。该接口方法有:
    • Modifier and TypeMethod and DescriptionEditableappend(char text)
      Convenience for append(String.valueOf(text)).
      Editableappend(CharSequence text)
      Convenience for replace(length(), length(), text, 0, text.length())
      Editableappend(CharSequence text, int start, int end)
      Convenience for replace(length(), length(), text, start, end)
      voidclear()
      Convenience for replace(0, length(), "", 0, 0)
      voidclearSpans()
      Removes all spans from the Editable, as if by calling Spannable.removeSpan(java.lang.Object) on each of them.
      Editabledelete(int st, int en)
      Convenience for replace(st, en, "", 0, 0)
      InputFilter[]getFilters()
      Returns the array of input filters that are currently applied to changes to this Editable.
      Editableinsert(int where, CharSequence text)
      Convenience for replace(where, where, text, 0, text.length());
      Editableinsert(int where, CharSequence text, int start, int end)
      Convenience for replace(where, where, text, start, end)
      Editablereplace(int st, int en, CharSequence text)
      Convenience for replace(st, en, text, 0, text.length())
      Editablereplace(int st, int en, CharSequence source, int start, int end)
      Replaces the specified range (st…en) of text in this Editable with a copy of the slice start…end from source.
      voidsetFilters(InputFilter[] filters)
      Sets the series of filters that will be called in succession whenever the text of this Editable is changed, each of which has the opportunity to limit or transform the text that is being inserted.
第二中方式:通过实现Spanned接口的相关类来实现。如:SpannableString类、SpannableStringBuilder类、SpannedString类。

例如:
    SpannableString ss = new SpannableString("红色打电话斜体删除线绿色下划线:.");
    ss.setSpan(new ForegroundColorSpan(Color.RED), 0, 2,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//设置指定前面2个字为红色
    ss.setSpan(new URLSpan("tel:4155551212"), 2, 5,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//指定第2到第5个文字点击为拨打电话:4155551212   
    ss.setSpan(new URLSpan("http://www.hao123.com"), 9, 11,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new URLSpan("sms:10086"), 13, 15,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 5, 7,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//指定文字样式
    ss.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 7, 10,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new UnderlineSpan(), 10, 16,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//指定文字下划横线
    ss.setSpan(new ImageSpan(d, ImageSpan.ALIGN_BASELINE), 18, 19, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//指定第18到第19个文字显示为图片。
    ssb.setSpan(new ClickableSpan() { 
             @Override
            public void onClick(View widget) { //处理点击事件
                  Toast.makeText(getView().getContext(), name, 
                 Toast.LENGTH_SHORT).show(); 
            } 
 
           @Override
            public void updateDrawState(TextPaint ds) { //处理可点击文字的样式
                 super.updateDrawState(ds); 
                 // ds.setColor(Color.RED); // 设置文本颜色 
               // 去掉下划线 
               ds.setUnderlineText(false); 
           } 
        }, 6, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //指定文本中的某些文字可点击

注: Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,这是在 setSpan 时需要指定的 flag。它是用来标识在 Span 范围内的文本前后输入新的字符时是否把它们也应用这个效果。分别有 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)、Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括,后面不包括)、Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括,后面包括)、Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)。

0 0
原创粉丝点击