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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM