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中要显示的内容 */ publicvoidsetMaxEcplise(finalTextViewmTextView,finalintmaxLines,finalStringcontent){
ViewTreeObserverobserver=mTextView.getViewTreeObserver(); observer.addOnGlobalLayoutListener(newOnGlobalLayoutListener(){ @Override publicvoidonGlobalLayout(){ mTextView.setText(content); if(mTextView.getLineCount()>maxLines){ intlineEndIndex=mTextView.getLayout().getLineEnd(maxLines-1); //下面这句代码中:我在项目中用数字3发现效果不好,改成1了
Stringtext=content.subSequence(0,lineEndIndex-3)+"..."; mTextView.setText(text); } else{ removeGlobalOnLayoutListener(mTextView.getViewTreeObserver(),this); } } }); }
@SuppressWarnings("deprecation") @SuppressLint("NewApi") privatevoidremoveGlobalOnLayoutListener(ViewTreeObserverobs,OnGlobalLayoutListenerlistener){ if(obs==null) return; if(Build.VERSION.SDK_INT<16){ obs.removeGlobalOnLayoutListener(listener); } else{ obs.removeOnGlobalLayoutListener(listener); } }
以上只是相关的方法代码,传入相应的参数就可以了。

更多相关文章

  1. mybatisplus的坑 insert标签insert into select无参数问题的解决
  2. Python技巧匿名函数、回调函数和高阶函数
  3. python list.sort()根据多个关键字排序的方法实现
  4. Android(安卓)Toast优化,不看别后悔
  5. android notification
  6. textView属性
  7. 滑条自动跳转,显示控件的新条目
  8. Android(安卓)TextView属性详解
  9. Android(安卓)TextView属性详解

随机推荐

  1. Android(安卓)已申请权限仍然提示 open f
  2. android客户端使用ssl连接mqtt服务器(单向
  3. Android(安卓)OutOfMemory 的思考
  4. Android(安卓)- 第二章 Activity 探究
  5. Android中如何开启变态混淆防止被反编译
  6. android native内存泄漏检测原理
  7. 【黑马Android】(19)response下载文件/验
  8. 安卓Android面试题汇总
  9. [置顶] Android(安卓)Paint之 setXfermod
  10. Android踩坑记录-混淆踩坑之(java.lang.N