1、TextView是android常用的组件之一,主要用来显示输出信息。 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设置行间距。
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一起使用,当文本不能全部显示时,后面用“…”来表示。如android:text="test_ singleLine "
android:singleLine="true" android:layout_width="20dp"将只显示“t…”。如果不设置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的基本属性了。但是简单的输出已经不满足我们日常开发的需要,这就需要我们在基本的功能上面添加自己的需求。
3、TextView常用的就是,图文混排(包括一部分文字的颜色字体变化)和文字跑马灯效果。这里博主就简单介绍一下,代码主要来源于别的博客,如有问题请勿喷水,谢谢。
3.1图文混排(来源于http://blog.csdn.net/leverage_1229/article/details/9320883)的基本效果
3.2技术要点:
1.创建attrs.xml文件用于设置自定义组件的属性、类型和样式。
2.利用android.content.res.TypedArray类将自定义组件装载到程序,以供程序调用。
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customTextView);
3.布局文件引入自定义组件需要如下设置
自定义组件命名空间(命名规则后文有详细介绍):
- xmlns:custom="http://schemas.android.com/apk/res/com.custom.textview"
xmlns:custom="http://schemas.android.com/apk/res/com.custom.textview"
自定义组件标签(类名):
- <com.custom.textview.CustomTextView .../>
<com.custom.textview.CustomTextView .../>
4.构造一个HashMap数据结构,用于保存自定义组件的内容类型和值。
key:自定义组件的内容类型(image、text)
value:自定义组件的内容值(imageUrl,CharSequence)
5.利用android.widget.LinearLayout.LayoutParams类用于设置组件的布局参数。这里需要根据显示内容的类型动态地设置组件的布局参数。
3.3
AndroidManifest.xml
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.custom.textview"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="15" />
- <uses-permission android:name="android.permission.INTERNET"/>
- <application
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name">
- <activity
- android:name=".MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.custom.textview"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
strings.xml
- <resources>
- <string name="app_name">自定义TextView实现图文并茂</string>
- </resources>
<resources>
<string name="app_name">自定义TextView实现图文并茂</string>
</resources>
自定义TextView组件的属性类型样式文件:attrs.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <declare-styleable name="customTextView">
- <attr name="image_width" format="dimension" />
- <attr name="image_height" format="dimension" />
- <attr name="text_color" format="color" />
- <attr name="text_size" format="dimension" />
- </declare-styleable>
- </resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="customTextView">
<attr name="image_width" format="dimension" />
<attr name="image_height" format="dimension" />
<attr name="text_color" format="color" />
<attr name="text_size" format="dimension" />
</declare-styleable>
</resources>
main.xml
- <?xml version="1.0" encoding="utf-8" ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:custom="http://schemas.android.com/apk/res/com.custom.textview"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:background="@android:color/white" >
- <com.custom.textview.CustomTextView
- android:id="@+id/textView"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- custom:image_width="200dp"
- custom:image_height="50dp" />
- </LinearLayout>
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.custom.textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@android:color/white" >
<com.custom.textview.CustomTextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:image_width="200dp"
custom:image_height="50dp" />
</LinearLayout>
自定义组件类:CustomTextView.java
- package com.custom.textview;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.HashMap;
- import android.content.Context;
- import android.content.res.TypedArray;
- import android.graphics.drawable.Drawable;
- import android.os.Handler;
- import android.os.Message;
- import android.os.SystemClock;
- import android.text.Html;
- import android.util.AttributeSet;
- import android.view.Gravity;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.TextView;
- public class CustomTextView extends LinearLayout {
- private Context context;
- private TypedArray typedArray;
- private LayoutParams params;
- public CustomTextView(Context context) {
- super(context);
- }
- public CustomTextView(Context context, AttributeSet attrs) {
- super(context, attrs);
- this.context = context;
- this.setOrientation(LinearLayout.VERTICAL);
- // 从attrs.xml中获取自定义属性
- typedArray = context.obtainStyledAttributes(attrs, R.styleable.customTextView);
- }
- public void setText(ArrayList<HashMap<String, String>> data) {
- for (HashMap<String, String> hashMap : data) {
- String type = hashMap.get("type");
- String value = hashMap.get("value");
- // 如果内容类型是图片
- if (type.equals("image")) {
- // 设置图片显示宽高、集中
- int imageWidth = typedArray.getDimensionPixelOffset(R.styleable.customTextView_image_width, 100);
- int imageHeight = typedArray.getDimensionPixelOffset(R.styleable.customTextView_image_height, 100);
- ImageView imageView = new ImageView(context);
- params = new LayoutParams(imageWidth, imageHeight);
- params.gravity = Gravity.CENTER_HORIZONTAL;
- imageView.setLayoutParams(params);
- // 显示默认图片
- imageView.setImageResource(R.drawable.ic_launcher);
- // 将ImageView添加到CustomTextView中
- addView(imageView);
- // 开启工作线程异步加载图片
- new DownloadWork(value, imageView).start();
- } else if (type.equals("text")) {
- int textColor = typedArray.getColor(R.styleable.customTextView_text_color, 0xFF0000FF);
- float textSize = typedArray.getDimension(R.styleable.customTextView_text_size, 16);
- TextView textView = new TextView(context);
- textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
- textView.setText(Html.fromHtml(value));
- textView.setTextColor(textColor);
- textView.setTextSize(textSize);
- addView(textView);
- }
- }
- }
- private class DownloadWork extends Thread {
- private String imageUrl;
- private ImageView imageView;
- public DownloadWork(String imageUrl, ImageView imageView) {
- this.imageUrl = imageUrl;
- this.imageView = imageView;
- }
- @Override
- public void run() {
- URL url = null;
- Drawable drawable = null;
- int newImageWidth = 0;
- int newImageHeight = 0;
- try {
- url = new URL(imageUrl);
- drawable = Drawable.createFromStream(url.openStream(), "image");
- // 对图片进行缩放
- newImageWidth = drawable.getIntrinsicWidth() / 3;
- newImageHeight = drawable.getIntrinsicHeight() / 3;
- } catch (Exception e) {
- e.printStackTrace();
- }
- SystemClock.sleep(2000);
- HashMap<String, Object> map = new HashMap<String, Object>();
- map.put("imageView", imageView);
- map.put("drawable", drawable);
- Message msg = handler.obtainMessage();
- msg.obj = map;
- msg.arg1 = newImageWidth;
- msg.arg2 = newImageHeight;
- handler.sendMessage(msg);
- }
- }
- private Handler handler = new Handler() {
- public void handleMessage(Message msg) {
- @SuppressWarnings("unchecked")
- HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
- ImageView imageView = (ImageView) map.get("imageView");
- LayoutParams params = new LayoutParams(msg.arg1, msg.arg2);
- params.gravity = Gravity.CENTER_HORIZONTAL;
- imageView.setLayoutParams(params);
- Drawable drawable = (Drawable) map.get("drawable");
- imageView.setImageDrawable(drawable);
- }
- };
- }
package com.custom.textview;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Html;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class CustomTextView extends LinearLayout {
private Context context;
private TypedArray typedArray;
private LayoutParams params;
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
this.setOrientation(LinearLayout.VERTICAL);
// 从attrs.xml中获取自定义属性
typedArray = context.obtainStyledAttributes(attrs, R.styleable.customTextView);
}
public void setText(ArrayList<HashMap<String, String>> data) {
for (HashMap<String, String> hashMap : data) {
String type = hashMap.get("type");
String value = hashMap.get("value");
// 如果内容类型是图片
if (type.equals("image")) {
// 设置图片显示宽高、集中
int imageWidth = typedArray.getDimensionPixelOffset(R.styleable.customTextView_image_width, 100);
int imageHeight = typedArray.getDimensionPixelOffset(R.styleable.customTextView_image_height, 100);
ImageView imageView = new ImageView(context);
params = new LayoutParams(imageWidth, imageHeight);
params.gravity = Gravity.CENTER_HORIZONTAL;
imageView.setLayoutParams(params);
// 显示默认图片
imageView.setImageResource(R.drawable.ic_launcher);
// 将ImageView添加到CustomTextView中
addView(imageView);
// 开启工作线程异步加载图片
new DownloadWork(value, imageView).start();
} else if (type.equals("text")) {
int textColor = typedArray.getColor(R.styleable.customTextView_text_color, 0xFF0000FF);
float textSize = typedArray.getDimension(R.styleable.customTextView_text_size, 16);
TextView textView = new TextView(context);
textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
textView.setText(Html.fromHtml(value));
textView.setTextColor(textColor);
textView.setTextSize(textSize);
addView(textView);
}
}
}
private class DownloadWork extends Thread {
private String imageUrl;
private ImageView imageView;
public DownloadWork(String imageUrl, ImageView imageView) {
this.imageUrl = imageUrl;
this.imageView = imageView;
}
@Override
public void run() {
URL url = null;
Drawable drawable = null;
int newImageWidth = 0;
int newImageHeight = 0;
try {
url = new URL(imageUrl);
drawable = Drawable.createFromStream(url.openStream(), "image");
// 对图片进行缩放
newImageWidth = drawable.getIntrinsicWidth() / 3;
newImageHeight = drawable.getIntrinsicHeight() / 3;
} catch (Exception e) {
e.printStackTrace();
}
SystemClock.sleep(2000);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("imageView", imageView);
map.put("drawable", drawable);
Message msg = handler.obtainMessage();
msg.obj = map;
msg.arg1 = newImageWidth;
msg.arg2 = newImageHeight;
handler.sendMessage(msg);
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
@SuppressWarnings("unchecked")
HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
ImageView imageView = (ImageView) map.get("imageView");
LayoutParams params = new LayoutParams(msg.arg1, msg.arg2);
params.gravity = Gravity.CENTER_HORIZONTAL;
imageView.setLayoutParams(params);
Drawable drawable = (Drawable) map.get("drawable");
imageView.setImageDrawable(drawable);
}
};
}
MainActivity.java
- package com.custom.textview;
- import java.util.ArrayList;
- import java.util.HashMap;
- import android.app.Activity;
- import android.os.Bundle;
- public class MainActivity extends Activity {
- private final String text = " <p> 今年浙江卫视凭《中国好声音》一举做大" +
- ",其巨大的影响力直接波及到了各家卫视“跨年晚会”的战略部署。日前" +
- ",“跨年晚会”概念的鼻祖湖南卫视率先表示“退出跨年烧钱大战”。" +
- "但据湖南卫视内部人士透露,即使如此,今年的湖南跨年晚会也将会掂出“跨年季”这个概念" +
- ",“也就是从12月27日到12月31日,连续五天,我们将相继用《百变大咖秀》、《快乐大本营》" +
- "、《女人如歌》、《天天向上》的特别节目来连续打造这个”季“的概念,直到12月31日的那场晚会。”</p>";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // 采集显示内容数据
- ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();
- HashMap<String, String> part1 = new HashMap<String, String>();
- part1.put("type", "image");
- part1.put("value", "http://www.linuxidc.com/upload/2012_12/121218101020341.png");
- HashMap<String, String> part2 = new HashMap<String, String>();
- part2.put("type", "text");
- part2.put("value", text);
- HashMap<String, String> part3 = new HashMap<String, String>();
- part3.put("type", "image");
- part3.put("value", "http://www.linuxidc.com/upload/2012_12/121218101020341.png");
- data.add(part1);
- data.add(part2);
- data.add(part3);
- CustomTextView customTextView = (CustomTextView) findViewById(R.id.textView);
- customTextView.setText(data);
- }
- }