facebook廣告





123

2017年1月28日 星期六

解決TextView中MaxLines與ellipsize=end衝突問題 原文網址:https://read01.com/A77M.html

https://read01.com/A77M.html

解決TextView中MaxLines與ellipsize=end衝突問題



TextView控制項有一個屬性是ellipsize,指的是當文字內容長度超過TextView大小時顯示問題,一般情況下我們都是用省略號表示,常用的情況有以下四種:
1,android:ellipsize = "end" 省略號在結尾
3,android:ellipsize = "start" 省略號在開頭
3,android:ellipsize = "middle" 省略號在中間
4,android:ellipsize = "marquee" 跑馬燈
但是我們遇到的問題是,這幾個屬性一般只有在設置了android:singleline = "true"的時候才有效,此時只能顯示一行文字,但是當我們的TextView要顯示多行文字,比如我們設置了android:maxLines="3"時,我們肯定不能設置android:singleline = "true",此時的android:ellipsize=「end」就失去效果了。MaxLines與ellipsize=end衝突問題糾結我很久,在網上打了不少資料,加上自己工作中的實際情況,寫了個工具類,測試了好幾款手機都沒有問題,把主要代碼貼出來,請大家多指教!


/**
* 參數:maxLines 要限制的最大行數
* 參數:content 指TextView中要顯示的內容
*/
public void setMaxEcplise(final TextView mTextView, final int maxLines, final String content) {
ViewTreeObserver observer = mTextView.getViewTreeObserver;
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener {
@Override
public void onGlobalLayout {
mTextView.setText(content);
if (mTextView.getLineCount > maxLines) {
int lineEndIndex = mTextView.getLayout.getLineEnd(maxLines - 1);


//下面這句代碼中:我在項目中用數字3發現效果不好,改成1了
String text = content.subSequence(0, lineEndIndex - 3) + "...";
mTextView.setText(text);
}
else {
removeGlobalOnLayoutListener(mTextView.getViewTreeObserver, this);
}
}
});
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void removeGlobalOnLayoutListener(ViewTreeObserver obs, OnGlobalLayoutListener listener) {
if (obs == null)
return;
if (Build.VERSION.SDK_INT < 16) {
obs.removeGlobalOnLayoutListener(listener);
}
else {
obs.removeOnGlobalLayoutListener(listener);
}
}
以上只是相關的方法代碼,傳入相應的參數就可以了。

沒有留言:

張貼留言