在上一文 给出了 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
本文介绍了解决TextView在多行显示末行使用省略号时,文字显示不准确的问题。通过计算末行文字宽度与显示区域的关系,实现了更精确的文本调整,确保文字完整显示而不超出屏幕范围。
1181

被折叠的 条评论
为什么被折叠?



