1 package com.sixin.view; 2 3 import android.content.Context; 4 import android.graphics.Canvas; 5 import android.text.Layout; 6 import android.text.StaticLayout; 7 import android.text.TextPaint; 8 import android.util.AttributeSet; 9 import android.widget.TextView; 10 11 /** 12 * 能够自动修正的textview,解决android自带textview右侧文字不能对齐的问题 13 */ 14 public class JustifyTextView extends TextView { 15 16 private int mLineY; 17 private int mViewWidth; 18 19 public JustifyTextView(Context context, AttributeSet attrs) { 20 super(context, attrs); 21 } 22 23 @Override 24 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 25 super.onLayout(changed, left, top, right, bottom); 26 } 27 28 @Override 29 protected void onDraw(Canvas canvas) { 30 TextPaint paint = getPaint(); 31 paint.setColor(getCurrentTextColor()); 32 paint.drawableState = getDrawableState(); 33 mViewWidth = getMeasuredWidth(); 34 String text = (String) getText(); 35 mLineY = 0; 36 mLineY += getTextSize(); 37 Layout layout = getLayout(); 38 for (int i = 0; i < layout.getLineCount(); i++) { 39 int lineStart = layout.getLineStart(i); 40 int lineEnd = layout.getLineEnd(i); 41 String line = text.substring(lineStart, lineEnd); 42 43 float width = StaticLayout.getDesiredWidth(text, lineStart, lineEnd, getPaint()); 44 if (needScale(line)) { 45 drawScaledText(canvas, lineStart, line, width); 46 } else { 47 canvas.drawText(line, 0, mLineY, paint); 48 } 49 50 mLineY += getLineHeight(); 51 } 52 } 53 54 private void drawScaledText(Canvas canvas, int lineStart, String line, float lineWidth) { 55 float x = 0; 56 if (isFirstLineOfParagraph(lineStart, line)) { 57 String blanks = " "; 58 canvas.drawText(blanks, x, mLineY, getPaint()); 59 float bw = StaticLayout.getDesiredWidth(blanks, getPaint()); 60 x += bw; 61 62 line = line.substring(3); 63 } 64 65 float d = (mViewWidth - lineWidth) / line.length() - 1; 66 for (int i = 0; i < line.length(); i++) { 67 String c = String.valueOf(line.charAt(i)); 68 float cw = StaticLayout.getDesiredWidth(c, getPaint()); 69 canvas.drawText(c, x, mLineY, getPaint()); 70 x += cw + d; 71 } 72 } 73 74 private boolean isFirstLineOfParagraph(int lineStart, String line) { 75 return line.length() > 3 && line.charAt(0) == ' ' && line.charAt(1) == ' '; 76 } 77 78 private boolean needScale(String line) { 79 if (line.length() == 0) { 80 return false; 81 } else { 82 return line.charAt(line.length() - 1) != '\n'; 83 } 84 } 85 86 }