Android下有众多的Widget,而TextView可以说是最基础的,或者说是最基本的的控件。和其它编程语言相同的label标签一样,一般用来显示固定长度的文本字符串。


一、实例

在介绍前先演示一下实例

Android UI系列:TextView显示文本_第1张图片

效果图一如上

布局文件text_view.xml

    

java代码TextViewActivity.java

package com.example.test;import android.app.Activity;import android.os.Bundle;public class TextViewActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.text_view);}}

再在AndroidManifest.xml配置一下

                                                                 

其中用的字符串资源是

我是Textview,大家要好好学习!

二、TextView类结构

java.lang.Object
   ↳     android.view.View
         ↳     android.widget.TextView


直接子类
Button, CheckedTextView, Chronometer, DigitalClock, EditText, TextClock

间接子类
AutoCompleteTextView, CheckBox, CompoundButton, ExtractEditText, MultiAutoCompleteTextView, RadioButton, Switch, ToggleButton 


Button,EditText,CheckBox,RadioButton,ToggleButton 等都是它的直接子类或间接子类,所以我们要一定学好TextView,才能更好地学习其它控件。


三、TextView属性

XML Attributes
Attribute Name Related Method Description
android:autoLink setAutoLinkMask(int) Controls whether links such as urls and email addresses are automatically found and converted to clickable links. 
android:autoText setKeyListener(KeyListener) If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. 
android:bufferType setText(CharSequence,TextView.BufferType) Determines the minimum type that getText() will return. 
android:capitalize setKeyListener(KeyListener) If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. 
android:cursorVisible setCursorVisible(boolean) Makes the cursor visible (the default) or invisible. 
android:digits setKeyListener(KeyListener) If set, specifies that this TextView has a numeric input method and that these specific characters are the ones that it will accept. 
android:drawableBottom setCompoundDrawablesWithIntrinsicBounds(int,int,int,int) The drawable to be drawn below the text. 
android:drawableEnd setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int) The drawable to be drawn to the end of the text. 
android:drawableLeft setCompoundDrawablesWithIntrinsicBounds(int,int,int,int) The drawable to be drawn to the left of the text. 
android:drawablePadding setCompoundDrawablePadding(int) The padding between the drawables and the text. 
android:drawableRight setCompoundDrawablesWithIntrinsicBounds(int,int,int,int) The drawable to be drawn to the right of the text. 
android:drawableStart setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int) The drawable to be drawn to the start of the text. 
android:drawableTop setCompoundDrawablesWithIntrinsicBounds(int,int,int,int) The drawable to be drawn above the text. 
android:editable   If set, specifies that this TextView has an input method. 
android:editorExtras setInputExtras(int) Reference to an XML resource containing additional data to supply to an input method, which is private to the implementation of the input method. 
android:ellipsize setEllipsize(TextUtils.TruncateAt) If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle. 
android:ems setEms(int) Makes the TextView be exactly this many ems wide. 
android:fontFamily setTypeface(Typeface) Font family (named by string) for the text. 
android:freezesText setFreezesText(boolean) If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. 
android:gravity setGravity(int) Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view. 
android:height setHeight(int) Makes the TextView be exactly this many pixels tall. 
android:hint setHint(int) Hint text to display when the text is empty. 
android:imeActionId setImeActionLabel(CharSequence,int) Supply a value for EditorInfo.actionId used when an input method is connected to the text view. 
android:imeActionLabel setImeActionLabel(CharSequence,int) Supply a value for EditorInfo.actionLabel used when an input method is connected to the text view. 
android:imeOptions setImeOptions(int) Additional features you can enable in an IME associated with an editor to improve the integration with your application. 
android:includeFontPadding setIncludeFontPadding(boolean) Leave enough room for ascenders and descenders instead of using the font ascent and descent strictly. 
android:inputMethod setKeyListener(KeyListener) If set, specifies that this TextView should use the specified input method (specified by fully-qualified class name). 
android:inputType setRawInputType(int) The type of data being placed in a text field, used to help an input method decide how to let the user enter text. 
android:lineSpacingExtra setLineSpacing(float,float) Extra spacing between lines of text. 
android:lineSpacingMultiplier setLineSpacing(float,float) Extra spacing between lines of text, as a multiplier. 
android:lines setLines(int) Makes the TextView be exactly this many lines tall. 
android:linksClickable setLinksClickable(boolean) If set to false, keeps the movement method from being set to the link movement method even if autoLink causes links to be found. 
android:marqueeRepeatLimit setMarqueeRepeatLimit(int) The number of times to repeat the marquee animation. 
android:maxEms setMaxEms(int) Makes the TextView be at most this many ems wide. 
android:maxHeight setMaxHeight(int) Makes the TextView be at most this many pixels tall. 
android:maxLength setFilters(InputFilter) Set an input filter to constrain the text length to the specified number. 
android:maxLines setMaxLines(int) Makes the TextView be at most this many lines tall. 
android:maxWidth setMaxWidth(int) Makes the TextView be at most this many pixels wide. 
android:minEms setMinEms(int) Makes the TextView be at least this many ems wide. 
android:minHeight setMinHeight(int) Makes the TextView be at least this many pixels tall. 
android:minLines setMinLines(int) Makes the TextView be at least this many lines tall. 
android:minWidth setMinWidth(int) Makes the TextView be at least this many pixels wide. 
android:numeric setKeyListener(KeyListener) If set, specifies that this TextView has a numeric input method. 
android:password setTransformationMethod(TransformationMethod) Whether the characters of the field are displayed as password dots instead of themselves. 
android:phoneNumber setKeyListener(KeyListener) If set, specifies that this TextView has a phone number input method. 
android:privateImeOptions setPrivateImeOptions(String) An addition content type description to supply to the input method attached to the text view, which is private to the implementation of the input method. 
android:scrollHorizontally setHorizontallyScrolling(boolean) Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally). 
android:selectAllOnFocus setSelectAllOnFocus(boolean) If the text is selectable, select it all when the view takes focus. 
android:shadowColor setShadowLayer(float,float,float,int) Place a shadow of the specified color behind the text. 
android:shadowDx setShadowLayer(float,float,float,int) Horizontal offset of the shadow. 
android:shadowDy setShadowLayer(float,float,float,int) Vertical offset of the shadow. 
android:shadowRadius setShadowLayer(float,float,float,int) Radius of the shadow. 
android:singleLine setTransformationMethod(TransformationMethod) Constrains the text to a single horizontally scrolling line instead of letting it wrap onto multiple lines, and advances focus instead of inserting a newline when you press the enter key. 
android:text setText(CharSequence,TextView.BufferType) Text to display. 
android:textAllCaps setAllCaps(boolean) Present the text in ALL CAPS. 
android:textAppearance   Base text color, typeface, size, and style. 
android:textColor setTextColor(int) Text color. 
android:textColorHighlight setHighlightColor(int) Color of the text selection highlight. 
android:textColorHint setHintTextColor(int) Color of the hint text. 
android:textColorLink setLinkTextColor(int) Text color for links. 
android:textIsSelectable isTextSelectable() Indicates that the content of a non-editable text can be selected. 
android:textScaleX setTextScaleX(float) Sets the horizontal scaling factor for the text. 
android:textSize setTextSize(int,float) Size of the text. 
android:textStyle setTypeface(Typeface) Style (bold, italic, bolditalic) for the text. 
android:typeface setTypeface(Typeface) Typeface (normal, sans, serif, monospace) for the text. 
android:width setWidth(int) Makes the TextView be exactly this many pixels wide. 

四、能过代码方式建立TextView

TextView可以通过在布局文件进行设置,也可以通过代码生成

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);TextView textView= new TextView(this);textView.setText(getText(R.string.textView_content));setContentView(textView);}

运行的效果和图一完全一样


五、走马灯效果

        android:ellipsize="marquee"        android:focusable="true"        android:focusableInTouchMode="true"        android:marqueeRepeatLimit="marquee_forever"        android:singleLine="true"

加上以上属性就可以实现走马灯的效果了

注意:

1.要单行,如果没有设置单行,多行可以全部显示出来,是没有走马灯的效果的

2.设置为焦点

3没有滚动球的设备 android:focusableInTouchMode="true"属性是必须的

4.如果内容一行就可以显示出来的,请重复一次内容,如果重复后还是可以一行显示的,请再重复,如

 我是Textview,大家要好好学习!我是Textview,大家要好好学习!


闪烁效果

别人的走马灯效果要闪烁一下,那我们也来实现

public class TextViewActivity extends Activity {private TextView textView = null;private boolean changeColor = false;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.text_view);textView = (TextView) findViewById(R.id.text_view);new Thread(new MyThread()).start();}//实现半秒就改变一次颜色class MyThread implements Runnable {@Overridepublic void run() {//传说中死循环,半秒就改变一次while (true) {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}Message message = new Message();if (changeColor = !changeColor) {message.what = COLOR_BLACK;} else {message.what = COLOR_RED;}handler.sendMessage(message);}}// end run}private final int COLOR_RED = 1;//红色private final int COLOR_BLACK = 2;//黑色private MyHandler handler = new MyHandler();class MyHandler extends Handler {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case COLOR_RED:textView.setTextColor(Color.RED);break;case COLOR_BLACK:textView.setTextColor(Color.BLACK);break;default:break;}}}}

以上的效果是半秒就改变一下字体的颜色,红黑不停地切换


六、在文本中创建上下文链接

如果TextView中的文本字符串包含有网址、邮箱、电话号码或地址,是否可以点击进行相应的跳转到我们要去的页面,如字符串的网址链接,跳到相应的网页,那样我们就可以直接查看内容了,这不是一件很美妙的事吗?

答案是确定的,我们可以对android:autoLink属性进行设置,或者调用 setAutoLinkMask(int)方法

Must be one or more (separated by '|') of the following constant values.

Constant Value Description
none 0x00 都不匹配 (default).
web 0x01 匹配网址链接
email 0x02 匹配email地址
phone 0x04 匹配电话号码
map 0x08 匹配地图地址.
all 0x0f 匹配所有(equivalent to web|email|phone|map).

例如xml设置

android:autoLink="web" 

android:autoLink="web|email"

android:autoLink="all"


java代码设置

textView.setAutoLinkMask(Linkify.EMAIL_ADDRESSES);

textView.setAutoLinkMask(Linkify.EMAIL_ADDRESSES|Linkify.WEB_URLS);

textView.setAutoLinkMask(Linkify.ALL);


七、获取本地资源及格式化

方法1

 public final CharSequence getText (int resId)

Return a localized, styled CharSequence from the application's package's default string table.

方法2

 public final String getString (int resId)

Return a localized string from the application's package's default string table.


方法3

getResources().getString(int resId)

Return the string value associated with a particular resource ID. It will be stripped of any styled text information.

演示:

Plain, bold, italic, bold-italic


text_view_1.setText(getText(R.string.text_format));text_view_2.setText(getString(R.string.text_format));text_view_3.setText(getResources().getString(R.string.text_format));



TextView 也可以支持html格式显示

主要是使用Html.fromHtml(String str)方法


String htmlStr="我是中国人
我你他也是中国人呀。";text_view_4.setText(Html.fromHtml(htmlStr));

string.xml特殊字符

string.xml中有特殊的字符,会报错的,那应该怎样解决呢

一个方法是用转义符,还有一个更简单的方法就是用形式


string.xml字符串中带参数

我是%1$s,我的年龄是%2$dtext_view_5.setText(getString(R.string.textview_param, "科学家",20));

结果显示:我是科学家,我的年龄是


%1$s       1表示第一个参数,s表示为字符串

%2$d      2表示第二个参数,d表示为数字,整数、小数都可以


八、显示图片


Android UI系列:TextView显示文本_第2张图片


上图是android桌面上的应用图标,应用名称上面是应用logo,这个怎样的实现的

是不是用了两个控件,一个是ImageView,另一个是TextView



其实不是,真正实现只是用了一个TextView

android:drawableTop表示是textView上面显示图片

android:drawableBottom表示底部显示图片

android:drawableLeft表示左边显示图片

android:drawableRight表示右边显示图片


九、属性介绍

android:ellipsize

内容过长时,可以加省略号
android:ellipsize = "none"  默认值,没有省略号
android:ellipsize = "end"    省略号在结尾 
android:ellipsize = "start"   省略号在开头 
android:ellipsize = "middle"    省略号在中间 
android:ellipsize = "marquee"  跑马灯 

注意要加行数限制,要不省略号不起作用

如 android:maxLines="2" 超过两行将出现省略号

或者android:singleLine="true"限制为1行



更多相关文章

  1. Android 存储字符串数据到txt文件
  2. Android 自定义PopupWindow实现悬浮窗效果
  3. Android中的四种动画效果
  4. Android下蒙板效果的实现
  5. Android学习之霓虹灯效果--所遇问题

随机推荐

  1. java链接数据库--Mysql
  2. MySQL常用命令与常见问题解决
  3. profiles在mysql中的应用
  4. 30分钟安装linux版本mysql5.7.21版本,没
  5. MySQL官网示例数据库emploees分析使用
  6. Mysql 查询—按位运算
  7. mysql——数据库设计中int与varchar中的
  8. CodeIgniter其中值IN(Field1,Field2)
  9. 'mysql'不是内部或外部命令,也不是可运行
  10. MVC框架——学生信息管理系统(多表,多事务