博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android获取textview的行数
阅读量:4328 次
发布时间:2019-06-06

本文共 1365 字,大约阅读时间需要 4 分钟。

 

最近项目需求,需要获取Textview的行数,通过行数与TextView的maxLines进行比较来确定是否显示TextView下方的展开按钮是否显示,废话少说直接上代码,mTextView.getLineCount() ,似乎很美好,安卓有提供这个方法,但是总是返回0,这是为啥呢?官方注释如下:

/**

* Return the number of lines of text, or 0 if the internal Layout has not
* been built.
*/

也就是说只有内部的Layout创建之后才会返回正确的行数,那怎么保证layout已经构创建了呢?

最后我是这么解决的

mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
Log.e(TAG, "行数"+mTextView.getLineCount());

 mTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

if(mTextView.getLineCount()>0){

 mTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

}

}
});

当TeXtView在绘制的时候就会回调这个方法,注意当我们得到了想要的值之后注意移除GlobalOnLayoutListener避免多余的执行,而且我的项目需求是要后面通过改变textview的高度实现平滑展开的动画。附上关键代码

/**

* 折叠效果
*/
tempHight = mTextView.getLineHeight() * mTextView.getLineCount() - startHight; //计算要展开高度

 tempHight = mTextView.getLineHeight() * maxLine - startHight;//为负值,收缩的高度

Animation animation = new Animation() {
//interpolatedTime 为当前动画帧对应的相对时间,值总在0-1之间
protected void applyTransformation(float interpolatedTime, Transformation t) { 
mTextView.setHeight((int) (startHight + tempHight * interpolatedTime));//原始长度+高度差*(从0到1的渐变)即表现为动画效果
}
};
animation.setDuration(1000);
mTextView.startAnimation(animation);

 

转载于:https://www.cnblogs.com/wutianlong/p/6256540.html

你可能感兴趣的文章
如何使用mysql
查看>>
linux下wc命令详解
查看>>
敏捷开发中软件测试团队的职责和产出是什么?
查看>>
在mvc3中使用ffmpeg对上传视频进行截图和转换格式
查看>>
python的字符串内建函数
查看>>
Spring - DI
查看>>
微软自己的官网介绍 SSL 参数相关
查看>>
Composite UI Application Block (CAB) 概念和术语
查看>>
ajax跨域,携带cookie
查看>>
阶段3 2.Spring_01.Spring框架简介_03.spring概述
查看>>
阶段3 2.Spring_02.程序间耦合_1 编写jdbc的工程代码用于分析程序的耦合
查看>>
阶段3 2.Spring_01.Spring框架简介_04.spring发展历程
查看>>
阶段3 2.Spring_02.程序间耦合_3 程序的耦合和解耦的思路分析1
查看>>
阶段3 2.Spring_02.程序间耦合_5 编写工厂类和配置文件
查看>>
阶段3 2.Spring_01.Spring框架简介_05.spring的优势
查看>>
阶段3 2.Spring_02.程序间耦合_7 分析工厂模式中的问题并改造
查看>>
阶段3 2.Spring_02.程序间耦合_4 曾经代码中的问题分析
查看>>
阶段3 2.Spring_03.Spring的 IOC 和 DI_2 spring中的Ioc前期准备
查看>>
阶段3 2.Spring_03.Spring的 IOC 和 DI_4 ApplicationContext的三个实现类
查看>>
阶段3 2.Spring_02.程序间耦合_8 工厂模式解耦的升级版
查看>>