您的位置:首页 > 产品设计 > UI/UE

Android UI系列:TextView显示文本

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

一、实例

在介绍前先演示一下实例



效果图一如上
布局文件text_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/textView_content" />
</LinearLayout>


java代码TextViewActivity.java

package com.example.test;

import android.app.Activity;
import android.os.Bundle;

public class TextViewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_view);
}
}


再在AndroidManifest.xml配置一下

<activity
android:name="TextViewActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>


其中用的字符串资源是

<string name="textView_content">我是Textview,大家要好好学习!</string>

二、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 NameRelated MethodDescription
android:autoLinksetAutoLinkMask(int)Controls whether links such as urls and email addresses are automatically found and converted to clickable links. 
android:autoTextsetKeyListener(KeyListener)If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. 
android:bufferTypesetText(CharSequence,TextView.BufferType)Determines the minimum type that getText() will return. 
android:capitalizesetKeyListener(KeyListener)If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. 
android:cursorVisiblesetCursorVisible(boolean)Makes the cursor visible (the default) or invisible. 
android:digitssetKeyListener(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:drawableBottomsetCompoundDrawablesWithIntrinsicBounds(int,int,int,int)The drawable to be drawn below the text. 
android:drawableEndsetCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int)The drawable to be drawn to the end of the text. 
android:drawableLeftsetCompoundDrawablesWithIntrinsicBounds(int,int,int,int)The drawable to be drawn to the left of the text. 
android:drawablePaddingsetCompoundDrawablePadding(int)The padding between the drawables and the text. 
android:drawableRightsetCompoundDrawablesWithIntrinsicBounds(int,int,int,int)The drawable to be drawn to the right of the text. 
android:drawableStartsetCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int)The drawable to be drawn to the start of the text. 
android:drawableTopsetCompoundDrawablesWithIntrinsicBounds(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:editorExtrassetInputExtras(int)Reference to an
<input-extras>
XML resource containing additional data to supply to an input method, which is private to the implementation of the input method. 
android:ellipsizesetEllipsize(TextUtils.TruncateAt)If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle. 
android:emssetEms(int)Makes the TextView be exactly this many ems wide. 
android:fontFamilysetTypeface(Typeface)Font family (named by string) for the text. 
android:freezesTextsetFreezesText(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:gravitysetGravity(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:heightsetHeight(int)Makes the TextView be exactly this many pixels tall. 
android:hintsetHint(int)Hint text to display when the text is empty. 
android:imeActionIdsetImeActionLabel(CharSequence,int)Supply a value for
EditorInfo.actionId
used when an input method is connected to the text view. 
android:imeActionLabelsetImeActionLabel(CharSequence,int)Supply a value for
EditorInfo.actionLabel
used when an input method is connected to the text view. 
android:imeOptionssetImeOptions(int)Additional features you can enable in an IME associated with an editor to improve the integration with your application. 
android:includeFontPaddingsetIncludeFontPadding(boolean)Leave enough room for ascenders and descenders instead of using the font ascent and descent strictly. 
android:inputMethodsetKeyListener(KeyListener)If set, specifies that this TextView should use the specified input method (specified by fully-qualified class name). 
android:inputTypesetRawInputType(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:lineSpacingExtrasetLineSpacing(float,float)Extra spacing between lines of text. 
android:lineSpacingMultipliersetLineSpacing(float,float)Extra spacing between lines of text, as a multiplier. 
android:linessetLines(int)Makes the TextView be exactly this many lines tall. 
android:linksClickablesetLinksClickable(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:marqueeRepeatLimitsetMarqueeRepeatLimit(int)The number of times to repeat the marquee animation. 
android:maxEmssetMaxEms(int)Makes the TextView be at most this many ems wide. 
android:maxHeightsetMaxHeight(int)Makes the TextView be at most this many pixels tall. 
android:maxLengthsetFilters(InputFilter)Set an input filter to constrain the text length to the specified number. 
android:maxLinessetMaxLines(int)Makes the TextView be at most this many lines tall. 
android:maxWidthsetMaxWidth(int)Makes the TextView be at most this many pixels wide. 
android:minEmssetMinEms(int)Makes the TextView be at least this many ems wide. 
android:minHeightsetMinHeight(int)Makes the TextView be at least this many pixels tall. 
android:minLinessetMinLines(int)Makes the TextView be at least this many lines tall. 
android:minWidthsetMinWidth(int)Makes the TextView be at least this many pixels wide. 
android:numericsetKeyListener(KeyListener)If set, specifies that this TextView has a numeric input method. 
android:passwordsetTransformationMethod(TransformationMethod)Whether the characters of the field are displayed as password dots instead of themselves. 
android:phoneNumbersetKeyListener(KeyListener)If set, specifies that this TextView has a phone number input method. 
android:privateImeOptionssetPrivateImeOptions(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:scrollHorizontallysetHorizontallyScrolling(boolean)Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally). 
android:selectAllOnFocussetSelectAllOnFocus(boolean)If the text is selectable, select it all when the view takes focus. 
android:shadowColorsetShadowLayer(float,float,float,int)Place a shadow of the specified color behind the text. 
android:shadowDxsetShadowLayer(float,float,float,int)Horizontal offset of the shadow. 
android:shadowDysetShadowLayer(float,float,float,int)Vertical offset of the shadow. 
android:shadowRadiussetShadowLayer(float,float,float,int)Radius of the shadow. 
android:singleLinesetTransformationMethod(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:textsetText(CharSequence,TextView.BufferType)Text to display. 
android:textAllCapssetAllCaps(boolean)Present the text in ALL CAPS. 
android:textAppearance Base text color, typeface, size, and style. 
android:textColorsetTextColor(int)Text color. 
android:textColorHighlightsetHighlightColor(int)Color of the text selection highlight. 
android:textColorHintsetHintTextColor(int)Color of the hint text. 
android:textColorLinksetLinkTextColor(int)Text color for links. 
android:textIsSelectableisTextSelectable()Indicates that the content of a non-editable text can be selected. 
android:textScaleXsetTextScaleX(float)Sets the horizontal scaling factor for the text. 
android:textSizesetTextSize(int,float)Size of the text. 
android:textStylesetTypeface(Typeface)Style (bold, italic, bolditalic) for the text. 
android:typefacesetTypeface(Typeface)Typeface (normal, sans, serif, monospace) for the text. 
android:widthsetWidth(int)Makes the TextView be exactly this many pixels wide. 

四、能过代码方式建立TextView

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

@Override
protected 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.如果内容一行就可以显示出来的,请重复一次内容,如果重复后还是可以一行显示的,请再重复,如

<string name="textView_content">我是Textview,大家要好好学习!我是Textview,大家要好好学习!</string>


闪烁效果

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

public class TextViewActivity extends Activity {
private TextView textView = null;
private boolean changeColor = false;

@Override
protected 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 {
@Override
public 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 {
@Override
public 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.

ConstantValueDescription
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.

演示:

<string name="text_format">Plain, <b>bold</b>, <i>italic</i>, <b><i>bold-italic</i></b></string>

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="我是<font color=red>中国人</font>。<br/>我你他也是<font color=green>中国人</font>呀。";
text_view_4.setText(Html.fromHtml(htmlStr));

string.xml特殊字符

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

一个方法是用转义符,还有一个更简单的方法就是用<![CDATA[]]>形式

<string name="other _format"><![CDATA[在这里输入特殊的字符,不会报错的]]></string>

string.xml字符串中带参数

<string name="textview_param">我是%1$s,我的年龄是%2$d</string>

text_view_5.setText(getString(R.string.textview_param, "科学家",20));


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

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

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

八、显示图片



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

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

<ImageView />

<TextView />

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

<TextView android:drawableTop="@drawable/ic_launcher"/>

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行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息