textView英文自动换行

我不是女神ヾ 2022-05-20 08:24 392阅读 0赞
  1. public class XRTextView extends TextView {
  2. private boolean mEnabled = true;
  3. public XRTextView(Context context) {
  4. super(context);
  5. }
  6. public XRTextView(Context context, AttributeSet attrs) {
  7. super(context, attrs);
  8. }
  9. public XRTextView(Context context, AttributeSet attrs, int defStyle) {
  10. super(context, attrs, defStyle);
  11. }
  12. public void setAutoSplitEnabled(boolean enabled) {
  13. mEnabled = enabled;
  14. }
  15. @Override
  16. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  17. if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY
  18. && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY
  19. && getWidth() > 0
  20. && getHeight() > 0
  21. && mEnabled) {
  22. String newText = autoSplitText(this);
  23. if (!TextUtils.isEmpty(newText)) {
  24. setText(newText);
  25. }
  26. }
  27. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  28. }
  29. private String autoSplitText(final TextView tv) {
  30. final String rawText = tv.getText().toString(); //原始文本
  31. final Paint tvPaint = tv.getPaint(); //paint,包含字体等信息
  32. final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度
  33. //将原始文本按行拆分
  34. String[] rawTextLines = rawText.replaceAll("\r", "").split("\n");
  35. StringBuilder sbNewText = new StringBuilder();
  36. for (String rawTextLine : rawTextLines) {
  37. if (tvPaint.measureText(rawTextLine) <= tvWidth) {
  38. //如果整行宽度在控件可用宽度之内,就不处理了
  39. sbNewText.append(rawTextLine);
  40. } else {
  41. //如果整行宽度超过控件可用宽度,则按字符测量,在超过可用宽度的前一个字符处手动换行
  42. float lineWidth = 0;
  43. for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {
  44. char ch = rawTextLine.charAt(cnt);
  45. lineWidth += tvPaint.measureText(String.valueOf(ch));
  46. if (lineWidth <= tvWidth) {
  47. sbNewText.append(ch);
  48. } else {
  49. sbNewText.append("\n");
  50. lineWidth = 0;
  51. --cnt;
  52. }
  53. }
  54. }
  55. sbNewText.append("\n");
  56. }
  57. //把结尾多余的\n去掉
  58. if (!rawText.endsWith("\n")) {
  59. sbNewText.deleteCharAt(sbNewText.length() - 1);
  60. }
  61. return sbNewText.toString();
  62. }
  63. public void setFont(String textFont) {
  64. Typeface lastTypeFace = getTypeface();
  65. boolean isBold = lastTypeFace != null ? lastTypeFace.isBold() : false;
  66. Typeface typeface = FontUtil.getTypeface(textFont, getContext());
  67. //使用字体
  68. setTypeface(typeface);
  69. //中文字体设置加粗
  70. TextPaint paint = getPaint();
  71. paint.setFakeBoldText(isBold);
  72. }
  73. }

发表评论

表情:
评论列表 (有 0 条评论,392人围观)

还没有评论,来说两句吧...

相关阅读