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);
}
});
以上表述可能有问题,希望自己以后看到能及时修改