赞
踩
-
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Paint;
- import android.util.AttributeSet;
- import android.widget.TextView;
-
- /**
- * 左对齐,然后 右边换行对齐,解决自动换行不整齐问题
- * lzx
- */
- public class AlignTextView extends TextView {
- private String text;
- private float textSize;
- private int textColor;
- private int paddingRight;
- private int paddingLeft;
- private Paint paint;
- private float textShowWidth;//可展示文本的宽度
- private float LineSpacing = 0f;
-
- public AlignTextView(Context context, AttributeSet attrs) {
- super(context, attrs);
- textSize = getTextSize();
- LineSpacing = getLineSpacingExtra();
- textColor = getCurrentTextColor();
- paddingLeft = getPaddingLeft();
- paddingRight = getPaddingRight();
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- if (paint == null) {
- paint = getPaint();
- paint.setAntiAlias(true);
- paint.setColor(textColor);
- }
- textShowWidth = canvas.getWidth() - paddingRight - paddingLeft;
- int lineCount = 1;
- text = this.getText().toString();
- char[] textCharArray = text.toCharArray();
- float drawedWidth = 0;
- float charWidth = paint.measureText(textCharArray, 0, 1);
- for (int i = 0; i < textCharArray.length; i++) {
- if (textCharArray[i] == '\n') {
- lineCount++;
- drawedWidth = 0;
- continue;
- }
- if (textShowWidth - drawedWidth < charWidth) {
- lineCount++;
- drawedWidth = 0;
- }
- canvas.drawText(textCharArray, i, 1, drawedWidth + paddingLeft,
- (lineCount) * textSize + (LineSpacing * (lineCount - 1)), paint);
- drawedWidth += charWidth;
- }
- }
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。