当前位置:   article > 正文

TextView 换行对齐自定义_android textview换行左对齐

android textview换行左对齐


  1. import android.content.Context;
  2. import android.graphics.Canvas;
  3. import android.graphics.Paint;
  4. import android.util.AttributeSet;
  5. import android.widget.TextView;
  6. /**
  7. * 左对齐,然后 右边换行对齐,解决自动换行不整齐问题
  8. * lzx
  9. */
  10. public class AlignTextView extends TextView {
  11. private String text;
  12. private float textSize;
  13. private int textColor;
  14. private int paddingRight;
  15. private int paddingLeft;
  16. private Paint paint;
  17. private float textShowWidth;//可展示文本的宽度
  18. private float LineSpacing = 0f;
  19. public AlignTextView(Context context, AttributeSet attrs) {
  20. super(context, attrs);
  21. textSize = getTextSize();
  22. LineSpacing = getLineSpacingExtra();
  23. textColor = getCurrentTextColor();
  24. paddingLeft = getPaddingLeft();
  25. paddingRight = getPaddingRight();
  26. }
  27. @Override
  28. protected void onDraw(Canvas canvas) {
  29. if (paint == null) {
  30. paint = getPaint();
  31. paint.setAntiAlias(true);
  32. paint.setColor(textColor);
  33. }
  34. textShowWidth = canvas.getWidth() - paddingRight - paddingLeft;
  35. int lineCount = 1;
  36. text = this.getText().toString();
  37. char[] textCharArray = text.toCharArray();
  38. float drawedWidth = 0;
  39. float charWidth = paint.measureText(textCharArray, 0, 1);
  40. for (int i = 0; i < textCharArray.length; i++) {
  41. if (textCharArray[i] == '\n') {
  42. lineCount++;
  43. drawedWidth = 0;
  44. continue;
  45. }
  46. if (textShowWidth - drawedWidth < charWidth) {
  47. lineCount++;
  48. drawedWidth = 0;
  49. }
  50. canvas.drawText(textCharArray, i, 1, drawedWidth + paddingLeft,
  51. (lineCount) * textSize + (LineSpacing * (lineCount - 1)), paint);
  52. drawedWidth += charWidth;
  53. }
  54. }
  55. }

就是取第一个字符,然后作为标准,绘制不到就换行,于是就不存在字符占用位置不够的问题

Java 文件

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

闽ICP备14008679号