关于TextView的一些初步解说
Android里面的textview是一个相当重要的类。相信做安卓的开发人员在每一个应用里面都一定用到了它,而且它也是Button,EditTextView等子控件的父类。
对于View的流程:measure ->layout -> draw ; measure会调用子类的onMeasure,同理layout调用子类的onLayout,draw会调用子类的onDraw(drawCanvas临时不讨论)。
先把大致流程理出来,然后我们去源代码里面找相应的函数(android-23里面相应的源代码)。
首先看下onMeasure()
方法里面干了什么事情
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//以上省略代码...
// 推断文字绘制的方向
if (mTextDir == null) {
mTextDir = getTextDirectionHeuristic();
}
int des = -1;
boolean fromexisting = false;
// 測量宽度
if (widthMode == MeasureSpec.EXACTLY) {
// Parent has told us how big to be. So be it.
width = widthSize;
} else {
if (mLayout != null && mEllipsize == null) {
des = desired(mLayout);
}
// BoringLayout.isBoring推断是否是单行文本(详细实现參见BoringLayout)
if (des < 0) {
boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
if (boring != null) {
mBoring = boring;
}
} else {
fromexisting = true;
}
//以上省略代码...
// 这里创建mLayout
if (mLayout == null) {
makeNewLayout(want, hintWant, boring, hintBoring,
width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false);
}
//以上省略代码...
// 设置測量好的宽高
setMeasuredDimension(width, height);
}
上面的代码主要去计算了textview显示的宽度以及构造出来了一个mLayout
,那继续看下调用makeNewLayout()
函数里面做了些什么:
/**
* The width passed in is now the desired layout width,
* not the full view width with padding.
* {@hide}
*/
protected void makeNewLayout(int wantWidth, int hintWidth,
BoringLayout.Metrics boring,
BoringLayout.Metrics hintBoring,
int ellipsisWidth, boolean bringIntoView) {
//以上省略代码...
// 这里真正产生mLayout
mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize,
effectiveEllipsize, effectiveEllipsize == mEllipsize);
//以上省略代码...
}
那我们进入makeSingleLayout()
的code:
private Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth,
Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize,
boolean useSaved) {
Layout result = null;
// 这里依据mText 的类型创建了3种不同的Layout
if (mText instanceof Spannable) {
result = new DynamicLayout(mText, mTransformed, mTextPaint, wantWidth,
alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad,
mBreakStrategy, mHyphenationFrequency,
getKeyListener() == null ? effectiveEllipsize : null, ellipsisWidth);
} else {
if (boring == UNKNOWN_BORING) {
boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring);
if (boring != null) {
mBoring = boring;
}
}
//以上省略代码...
// 以下使用Builder模式创建StaticLayout
if (result == null) {
StaticLayout.Builder builder = StaticLayout.Builder.obtain(mTransformed,
0, mTransformed.length(), mTextPaint, wantWidth)
.setAlignment(alignment)
.setTextDirection(mTextDir)
.setLineSpacing(mSpacingAdd, mSpacingMult)
.setIncludePad(mIncludePad)
.setBreakStrategy(mBreakStrategy)
.setHyphenationFrequency(mHyphenationFrequency);
if (shouldEllipsize) {
builder.setEllipsize(effectiveEllipsize)
.setEllipsizedWidth(ellipsisWidth)
.setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE);
}
// TODO: explore always setting maxLines
result = builder.build();
}
return result;
}
介绍下TextView的基本渲染原理,总的来说。TextView中负责渲染文字的主要是这三个类:
BoringLayout
主要负责显示单行文本。并提供了isBoring方法来推断是否满足单行文本的条件。DynamicLayout
当文本为Spannable的时候。TextView就会使用它来负责文本的显示,在内部设置了SpanWatcher。当检測到span改变的时候,会进行reflow,又一次计算布局。StaticLayout
当文本为非单行文本。且非Spannable的时候,就会使用StaticLayout,内部并不会监听span的变化,因此效率上会比 DynamicLayout高,仅仅需一次布局的创建就可以,但事实上内部也能显示SpannableString,仅仅是不能在span变化之后又一次进行布局而已。
这里引出一个有一个Spannable
是一个接口,它的实现类有SpannableString
,SpannableStringBuilder
,当我们在使用textView.setText()
的时候能够传入这2种类型的參数,举个样例比方我们须要在textview里面显示一个emoji表情:
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.hanguo);
ImageSpan imgSpan = new ImageSpan(this, b);
SpannableString spanString = new SpannableString("icon");
spanString.setSpan(imgSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanString);
这里都是图片塞入SpannableString
然后利用textView.setText
。假设你须要加入多个能够用SpannableStringBuilder
。
回归主线,之前我们把onMeasure
和onLayout
2个方法大体思路看完了,如今该去看看它的onDraw
里面做了一些哪些魔法的事情。
@Override
protected void onDraw(Canvas canvas) {
// 绘制相应xml里面drawLeft等4个方向的图片
final int compoundPaddingLeft = getCompoundPaddingLeft();
final int compoundPaddingTop = getCompoundPaddingTop();
final int compoundPaddingRight = getCompoundPaddingRight();
final int compoundPaddingBottom = getCompoundPaddingBottom();
// 省略很多代码...
if (mEditor != null) {
mEditor.onDraw(canvas, layout, highlight, mHighlightPaint, cursorOffsetVertical);
} else {
// 这里真的绘制调用了layout的draw,就是之前产生3中Layout中的当中一种
layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical);
}
主要做法先绘制drawLeft等4个方向的图片(假设有的话),再调用layout.draw()
去绘制文字,好的我们进入里面去看下
/**
* Draw this Layout on the specified canvas, with the highlight path drawn
* between the background and the text.
*
* @param canvas the canvas
* @param highlight the path of the highlight or cursor; can be null
* @param highlightPaint the paint for the highlight
* @param cursorOffsetVertical the amount to temporarily translate the
* canvas while rendering the highlight
*/
public void draw(Canvas canvas, Path highlight, Paint highlightPaint,
int cursorOffsetVertical) {
final long lineRange = getLineRangeForDraw(canvas);
int firstLine = TextUtils.unpackRangeStartFromLong(lineRange);
int lastLine = TextUtils.unpackRangeEndFromLong(lineRange);
if (lastLine < 0) return;
drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical,
firstLine, lastLine);
drawText(canvas, firstLine, lastLine);
}
代码非常短。看方法命名都知道
- 先绘制背景
- 绘制文字
我们主要关心怎么绘制文字信息的。看下
public void drawText(Canvas canvas, int firstLine, int lastLine) {
// 省略他大爷的那么多代码
if (directions == DIRS_ALL_LEFT_TO_RIGHT && !mSpannedText && !hasTabOrEmoji) {
// XXX: assumes there's nothing additional to be done
canvas.drawText(buf, start, end, x, lbaseline, paint);
} else {
tl.set(paint, buf, start, end, dir, directions, hasTabOrEmoji, tabStops);
tl.draw(canvas, x, ltop, lbaseline, lbottom);
}
paint.setHyphenEdit(0);
}
TextLine.recycle(tl);
}
主要看到了drawText()
,心里的石头放下来了;可是这里又有2中情况:
- 仅仅有文本信息
直接调用canvas.drawText
- 包括图片信息
使用TextLine的draw()
绘制。去TextLine的draw()里面:
void draw(Canvas c, float x, int top, int y, int bottom) {
if (!mHasTabs) {
if (mDirections == Layout.DIRS_ALL_LEFT_TO_RIGHT) {
// 这里会调用TextLine的handleRun(),里面的span.updateDrawState(wp),能够改变文字的颜色和下划线是否显示
drawRun(c, 0, mLen, false, x, top, y, bottom, false);
return;
}
// 省略代码...
if (emojiRect == null) {
emojiRect = new RectF();
}
emojiRect.set(x + h, y + bmAscent,
x + h + width, y);
// 这里调用drawBitmap绘制图片
c.drawBitmap(bm, null, emojiRect, mPaint);
h += width;
j++;
}
segstart = j + 1;
}
}
}
}
好了TextView的初步解说就到这里,这里推荐一个库,同学们有时间能够看下,能够借鉴大神的一些写法:textview的基本演示样例
关于TextView的一些初步解说的更多相关文章
- windows和Linux内存的对齐方式
一.内存对齐的初步解说 内存对齐能够用一句话来概括: "数据项仅仅能存储在地址是数据项大小的整数倍的内存位置上" 比如int类型占用4个字节,地址仅仅能在0,4,8等位置上. 例1 ...
- Dagger2 使用初步
Dagger2 是一个Android依赖注入框架,由谷歌开发,最早的版本Dagger1 由Square公司开发.依赖注入框架主要用于模块间解耦,提高代码的健壮性和可维护性.Dagger 这个库的取名不 ...
- android在代码中四种设置控件(以及TextView的文字颜色)背景颜色的方法
http://blog.csdn.net/fth826595345/article/details/9208771 主题 TextView 转载请注明出处: http://blog.csdn.ne ...
- 解说mysql之binlog日志以及利用binlog日志恢复数据
众所周知,binlog日志对于mysql数据库来说是十分重要的.在数据丢失的紧急情况下,我们往往会想到用binlog日志功能进行数据恢复(定时全备份+binlog日志恢复增量数据部分),化险为夷! 废 ...
- Android开发--TextView的应用
1.概述 TextView主要用于Activity中文本的应用.其中layout中xml文件(activity)设置文本的宽度,高度,ID:values中strings.xml设置文本内容. Text ...
- Android_Mars学习笔记_S01_001activity初步
一.activity初步 1.程序启动会先读配置文件AndroidManifest.xml找activity 2.activity会在onCreate方法中读取activity_main.xml文件, ...
- android_Intent对象初步(Activity传统的价值观念)
说明:初步Intent物.主要使用Intent对象在Activity之间传递数据的方法. 样例:由MainActivity→OtherActivity的跳转过程中,把数据传递给OtherActivit ...
- Cocos2d-x内存管理解说在ios开发中
使用过 Cocos2d-x 都知道,其中有一套自己实现的内存管理机制,不同于一般 C++ 的编写常规,而在使用前,了解其原理是有必要的,网上已经有很多对内部实现详细解说的文章.而对于使用者而言,并不需 ...
- VC6 下 libpng 库的编译与初步使用
VC6 下 libpng 库的编译与初步使用 目录 libong 库的介绍 VC6 下 libpng 的编译 下载 libpng 与 zlib 进行编译 得到 .lib 文件 初步使用 对 VC6 ...
随机推荐
- Python strings, 元组tuples, 和numbers是不可更改的对象,而list,dict等则是可以修改的
在python中,strings, 元组tuples, 和numbers是不可更改的对象,而list,dict等则是可以修改的对象. a = 1 def fun(a): a = 2 fun(a ...
- $(document).ready()方法和window.onload()方法
$(document).ready()方法和window.onload()方法 $(document).ready()方法是JQuery中的方法,他在DOM完全就需时就可以被调用,不必等待这些元素关联 ...
- hdu 3572 Task Schedule(最大流&&建图经典&&dinic)
Task Schedule Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) To ...
- struts2 常用标签
版权声明:本文为博主原创文章,未经博主允许不得转载. Struts2可以将所有标签分成3类: 准备工作:需要在JSP页面引入标签库 <%@ taglib prefix="s" ...
- 【SSH之旅】一步步学习Struts1框架(二):Struts实例
从上篇博客能够看到,事实上Struts1框架就是封装了一些页面的转向.数据类型的转换,去除冗余的if else推断.除了这些,事实上还封装了一些我们寻经常使用的JSTL标签库,文件上传等等. 以下看怎 ...
- 小电流MOS管
N沟道: 2n7000 Id=0.35A 2n7002 Id=0.2A
- kali2.0下配置Metasploit+postgresql链接
工具/原料 kali2.0 方法/步骤 1.postgresql是本身没有启动的.所以需要启动. service postgresql start 2.通过命令进入配置 sudo -u ...
- RESTORE DATABASE命令还原SQLServer 数据库 bak
今天在sqlServer20005 的management studio里使用bak文件还原数据库的时候,总是失败!Restore failed for Server 'ADANDELI'. (Mi ...
- DiskLrucCache使用Demo(强烈推荐,非常好用)
DiskLrucCache使用的Demo,这个demo是从网络获取一张图片,保存到本地缓存中(sdcard和内存),当下载成功后.再打开不会又一次向网络请求图片.而是世界使用本地资源. 要使用Disk ...
- Atitit .linux 取回root 密码q99
Atitit .linux 取回root 密码q99 1.1. 停止mysql1 1.2. mysqld_safe路径1 1.3. Mysql配置文件路径1 1.4. Mysql路径1 1.5. 安全 ...