当前位置:   article > 正文

解决android textview自动换行问题_android textview 自动换行

android textview 自动换行

  1. public class SDAdaptiveTextView extends TextView {
  2. public SDAdaptiveTextView(Context context) {
  3. super(context);
  4. }
  5. public SDAdaptiveTextView(Context context, @Nullable AttributeSet attrs) {
  6. super(context, attrs);
  7. }
  8. public SDAdaptiveTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  9. super(context, attrs, defStyleAttr);
  10. }
  11. /**
  12. * 使用该方法设置TextView的文本内容,改方法不能再主线程中执行
  13. * @param text
  14. */
  15. public void setAdaptiveText(String text) {
  16. this.setText(text);
  17. this.setText(adaptiveText(this));
  18. }
  19. private String adaptiveText(final TextView textView) {
  20. final String originalText = textView.getText().toString(); //原始文本
  21. final Paint tvPaint = textView.getPaint();//获取TextView的Paint
  22. final float tvWidth = textView.getWidth() - textView.getPaddingLeft() - textView.getPaddingRight(); //TextView的可用宽度
  23. //将原始文本按行拆分
  24. String[] originalTextLines = originalText.replaceAll("\r", "").split("\n");
  25. StringBuilder newTextBuilder = new StringBuilder();
  26. for (String originalTextLine : originalTextLines) {
  27. //文本内容小于TextView宽度,即不换行,不作处理
  28. if (tvPaint.measureText(originalTextLine) <= tvWidth) {
  29. newTextBuilder.append(originalTextLine);
  30. } else {
  31. //如果整行宽度超过控件可用宽度,则按字符测量,在超过可用宽度的前一个字符处手动换行
  32. float lineWidth = 0;
  33. for (int i = 0; i != originalTextLine.length(); ++i) {
  34. char charAt = originalTextLine.charAt(i);
  35. lineWidth += tvPaint.measureText(String.valueOf(charAt));
  36. if (lineWidth <= tvWidth) {
  37. newTextBuilder.append(charAt);
  38. } else {
  39. //单行超过TextView可用宽度,换行
  40. newTextBuilder.append("\n");
  41. lineWidth = 0;
  42. --i;//该代码作用是将本轮循环回滚,在新的一行重新循环判断该字符
  43. }
  44. }
  45. }
  46. }
  47. return newTextBuilder.toString();
  48. }
  49. }

 

  • 使用 setAdaptiveText 方法替代 原生的 setText 方法,注意该方法不能再主线程中执行
  • 如果TextView宽度设置为WrapContent,为了测量它的准确宽度,可先使用setText()方法设值,再调用setAdaptiveText()设值
    举例使用:

使用

  1. tvSdAdaptive.post(new Runnable() {
  2. @Override
  3. public void run() {
  4. tvSdAdaptive.setAdaptiveText("");
  5. }
  6. });
  1. tvSdAdaptive.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  2. @Override
  3. public void onGlobalLayout() {
  4. tvSdAdaptive.setAdaptiveText("");
  5. tvSdAdaptive.getViewTreeObserver().removeOnGlobalLayoutListener(this);
  6. }
  7. });

转载: https://www.jianshu.com/p/3f2ecfd13b69

个人学习用

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/242804?site
推荐阅读
相关标签
  

闽ICP备14008679号