TextView获取行数

API :getLineCount()

问题:

直接使用getLineCount()获取行数返回为0,因为测量TextView的行数需要TextView绘制完成,才能进行测量

解决:

方法一:
监听到TextView绘制完成,在对TextView进行测量

tv.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int mCount = tv.getLineCount();
        }
    });

方法二
post内容通过handler发送到消息队列等待UI线程执行

 tv.post(new Runnable() {
     @Override
     public void run() {
        int mCount = tv.getLineCount();
     }
});

简单TextView的折叠动画效果(摘录)

//设置默认显示高度
mTextView.setHeight(mTextView.getLineHeight() * maxLine); 

mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isExpand = !isExpand;
                mTextView.clearAnimation();  //清除动画
                final int tempHight;
                final int startHight = mTextView.getHeight();  //起始高度
                int durationMillis = 2000;

                if (isExpand) {    
                    //为正值,长文减去短文的高度差            
                   tempHight = mTextView.getLineHeight() * mTextView.getLineCount() - startHight;  

                   RotateAnimation animation = new RotateAnimation(0,180, 
                        Animation.RELATIVE_TO_SELF, 0.5f, 
                        Animation.RELATIVE_TO_SELF, 0.5f);
                    animation.setDuration(durationMillis);
                    animation.setFillAfter(true);
                    mImageView.startAnimation(animation);
                } else {
                    //为负值,即短文减去长文的高度差
                   tempHight = mTextView.getLineHeight() * maxLine - startHight;
                    // 翻转动画
                   RotateAnimation animation = newRotateAnimation(180,0, 
                        Animation.RELATIVE_TO_SELF, 0.5f, 
                        Animation.RELATIVE_TO_SELF, 0.5f);
                    animation.setDuration(durationMillis);
                    animation.setFillAfter(true);
                    mImageView.startAnimation(animation);

                Animation animation = new Animation() {
                    // interpolatedTime 为当前动画帧对应的相对时间,值总在0-1之间
                    protected void applyTransformation(float interpolatedTime, Transformation t) {
                        //根据ImageView旋转动画的百分比来显示textview高度,达到动画效果
                        mTextView.setHeight((int) (startHight + tempHight * interpolatedTime));
                        //原始长度+高度差*(从0到1的渐变)即表现为动画效果
                    }
                };

                animation.setDuration(durationMillis);
                mTextView.startAnimation(animation);
            }
        });  

以上表述可能有问题,希望自己以后看到能及时修改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值