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);         }     }
以上只是相关的方法代码,传入相应的参数就可以了。

更多相关文章

  1. 通过JavaScript或PHP检测Android设备的代码
  2. android 软件更新代码
  3. Ubuntu 下 Android源代码下载指南
  4. android textview 中超出屏幕宽度的字符 省略号显示
  5. Android中图像变换Matrix的原理、代码验证和应用(一)
  6. Android系列之Android开发教程代码实例
  7. 自定义SeekBarPreference控件(老外出品,直接在preferences文件中

随机推荐

  1. CentOS 6.5安装配置LNMP服务器(Nginx+PHP+
  2. Linux内核数据结构之链表
  3. LINUX使用ps命令获取对应PID
  4. 关于使用samba用户的权限设置
  5. 给VMware下的Linux扩展磁盘空间(以CentOS6
  6. linux 输入参数利用getopt、struct optio
  7. Linux内核黑客的虚拟环境
  8. Awk 命令学习总结、AWk命令系列学习(linux
  9. Linux Mint 18.1安装nvidia驱动
  10. Linux: xclip,pbcopy,xsel用法 terminal