在上一文 给出了 textview多行设置ellipsize="end"并不显示省略号的解决方法(当然如果不是中文 android-textview-multiline-ellipse 也是个解决方案)。上一文中通过measureText计算出最后一行的文字是否超出了显示范围,由于文字的宽度不是均匀的,所以这个方法在某些时候就会出现多一两个字或少一两个字。
下面给出第二中解决方法的主要代码:
protected void onDraw(Canvas canvas) { if (HAS_BUG && !mChecked) { mChecked = true; Layout layout = super.getLayout(); int maxLinex = mMaxLines > 0 ? mMaxLines : 1; if (layout.getLineCount() > maxLinex) { if (mELLIPSEWidth == 0) { mELLIPSEWidth = (int) getPaint().measureText(ELLIPSE_END); } mOriText = super.getText(); int width = layout.getWidth(), llw = (int) layout.getLineWidth(maxLinex-1), lci = layout.getLineEnd(maxLinex-1); if (mELLIPSEWidth + llw > width) { int spc = mELLIPSEWidth + llw - width; int w = (int) (spc / super.getTextSize()); if (spc % super.getTextSize() != 0) { ++w; } lci -= w; } super.setText(mOriText.subSequence(0, lci) + ELLIPSE_END); } } super.onDraw(canvas); }
下面是显示效果
附该控件源码。需要示例的请移步 textviewellipseendfixed