android获取textview的行数

 

最近项目需求,需要获取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