美文网首页
当TextView设置ellipsize ="end&

当TextView设置ellipsize ="end&

作者: 小木桨 | 来源:发表于2016-06-29 18:53 被阅读3813次

当TextView文本过长或全是emoji表情的时候,设置ellipsize ="end/start/middle"就会无效

解决方案:

  1. 创建一个自定义类并且实现OnGlobalLayoutListener接口
public class OnGlobalLayoutListenerByEllipSize implements ViewTreeObserver.OnGlobalLayoutListener {

   private TextView mTextView; 
   private int mMaxLines;  //最大行数

   public OnGlobalLayoutListenerByEllipSize(TextView textView,int maxLines){
       if(maxLines <= 0)
           throw new IllegalArgumentException("maxLines不能小于等于0");
       this.mTextView = textView;
       this.mMaxLines = maxLines;
       this.mTextView.setMaxLines(mMaxLines+1);
       this.mTextView.setSingleLine(false);
   }

   @Override
   public void onGlobalLayout() {
       if(mTextView.getLineCount() > mMaxLines){
           int line = mTextView.getLayout().getLineEnd(mMaxLines-1);
           CharSequence truncate = "...";//定义成CharSequence类型,是为了兼容emoji表情,如果使用String类型则会造成emoji无法显示
           CharSequence text = mTextView.getText();
           try {
               text = text.subSequence(0, line - 3);
           }catch (Exception e){
               truncate = "";
               text = mTextView.getText();
           }
           TextUtils.TruncateAt at = mTextView.getEllipsize();
           if(at == TextUtils.TruncateAt.START) {
               mTextView.setText(truncate);
               mTextView.append(text);
           }else if(at == TextUtils.TruncateAt.MIDDLE){
               mTextView.setText(text.subSequence(0,text.length()/2));
               mTextView.append(truncate);
               mTextView.append(text.subSequence(text.length()/2,text.length()));
           }else {
               mTextView.setText(text);
               mTextView.append(truncate);
           }
       }
   }
}
  1. 将自定义类OnGlobalLayoutListenerByEllipSize设置到TextView
mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListenerByEllipSize(mTextView,1));

相关文章

网友评论

      本文标题:当TextView设置ellipsize ="end&

      本文链接:https://www.haomeiwen.com/subject/ynsxjttx.html