700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Android中TextView文本或富文本内容自行换行的问题

Android中TextView文本或富文本内容自行换行的问题

时间:2021-01-05 13:48:10

相关推荐

Android中TextView文本或富文本内容自行换行的问题

Android中TextView设置文本或富文本的时候出现没有到头就换行的问题.

网上有很多相关内容. 但大多都是关于文本换行的情况, 对于有富文本内容的情况, 如设置Spanned对象的内容, 会出现颜色等内容丢失的情况. 在此基础上添加富文本内容的处理. 之前代码不知道原出处在哪, 在此借用一下.

如图显示内容:

废话少说, 上菜~~~~~~

1.对TextView进行监听.

private void initAutoSplitTextView() {mContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {mContent.getViewTreeObserver().removeOnGlobalLayoutListener(this);final CharSequence newText = autoSplitText(mContent);if (!TextUtils.isEmpty(newText)) {mContent.setText(newText);}}});}

2.对TextView显示内容的拆分.

//返回CharSequence对象private CharSequence autoSplitText(final TextView tv) {//tv.getText(), 原始的CharSequence内容.CharSequence charSequence = tv.getText();final String rawText = tv.getText().toString(); //原始文本final Paint tvPaint = tv.getPaint(); //paint,包含字体等信息final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度//将原始文本按行拆分String[] rawTextLines = rawText.replaceAll("\r", "").split("\n");StringBuilder sbNewText = new StringBuilder();for (String rawTextLine : rawTextLines) {if (tvPaint.measureText(rawTextLine) <= tvWidth) {//如果整行宽度在控件可用宽度之内,就不处理了sbNewText.append(rawTextLine);} else {//如果整行宽度超过控件可用宽度,则按字符测量,在超过可用宽度的前一个字符处手动换行float lineWidth = 0;for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {char ch = rawTextLine.charAt(cnt);lineWidth += tvPaint.measureText(String.valueOf(ch));if (lineWidth <= tvWidth) {sbNewText.append(ch);} else {sbNewText.append("\n");lineWidth = 0;--cnt;}}}sbNewText.append("\n");}//把结尾多余的\n去掉if (!rawText.endsWith("\n")) {sbNewText.deleteCharAt(sbNewText.length() - 1);}//对于有富文本的情况if (charSequence instanceof Spanned) {SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(charSequence);if (sbNewText.toString().contains("\n")) {String[] split = sbNewText.toString().split("\n");int tempIndex = 0;for (int i = 0; i < split.length; i++) {if (i != split.length - 1) {String s = split[i];tempIndex = tempIndex + s.length() + i;spannableStringBuilder.insert(tempIndex, "\n");}}}return spannableStringBuilder;} else {return sbNewText;}}

随手Mark, 如有问题留言一块探讨.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。