zoukankan      html  css  js  c++  java
  • 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);

  • 相关阅读:
    文件和目录之文件访问权限
    文件和目录之设置用户ID和设置组ID
    文件和目录之文件类型
    文件和目录之stat、fstat和lstat函数
    实用编程技术之多个头文件中变量的重复定义
    带缓冲I/O和不带缓冲I/O的区别与联系
    如何使用nodejs发邮件
    cosmic_download-AsyncPool待修正
    python性能分析之line_profiler模块
    python性能分析之cProfile模块
  • 原文地址:https://www.cnblogs.com/sharkli/p/5495206.html
Copyright © 2011-2022 走看看