我们知道,要使TextView单行显示,如果超出的话用“…”显示,只要设置
android:ellipsize="end"
android:singleLine="true"
或者多行显示,超出的部分使用“…”显示,那么,设置如下
android:lines="2"
android:ellipsize="end"
那么问题是,我们怎么知道TextView已经省略了内容呢?
TextView textView = (TextView) findViewById(R.id.txt_course_introduce);
Layout l=textView.getLayout();
if(l!=null){
int lines =l.getLineCount();
LogUtils.d(TAG, "lines = " + lines);
if(lines>0){
if(l.getEllipsisCount(lines-1)>0){
LogUtils.d(TAG, "Text is ellipsized");
}
}
}else {
LogUtils.d(TAG,"Layout is null");
}
通过textview获取Layout,然后根据Layout的一个方法getEllipsisCount(int),来判断是否已经省略,但Layout大多时候获取到的都是null,为什么呢?原因是,Layout要等TextView绘制完了才能够拿到Layout的对象。
final TextView textView = (TextView) findViewById(R.id.txt_training_introduce);
textView.post(new Runnable() {
@Override
public void run() {
Layout l = textView.getLayout();
if (l != null) {
int lines = l.getLineCount();
LogUtils.d(TAG, "lines = " + lines);
if (lines > 0) {
if (l.getEllipsisCount(lines - 1) > 0) {
LogUtils.d(TAG, "Text is ellipsized");
}
}
} else {
LogUtils.d(TAG, "Layout is null");
}
}
});