public class MyTextView extends TextView { private int textSize = 25; private int textColor = R.color.black; private String text; private Paint paint; private boolean hasDrawed = false; private List<String> lines; public DiskNameTextView(Context context, AttributeSet attrs) { super(context, attrs); textSize = attrs.getAttributeIntValue( "http://schemas.android.com/apk/res/android", "textSize", 28); textColor = attrs.getAttributeIntValue( "http://schemas.android.com/apk/res/android", "textColor", R.color.black); paint = new Paint(); paint.setTextSize(textSize); paint.setColor(textColor); paint.setStyle(Style.FILL); paint.setAntiAlias(true); } @SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (text != null && !text.trim().equals("")) { if(lines != null) { //先把每行文字保存起来,重画的时候加快速度 for(int i=0; i<lines.size(); i++) { canvas.drawText(lines.get(i), 0, (i+1) * textSize, paint); } return; } int viewWidth = this.getWidth(); // 得到view的宽度 int textWidth = (int) paint.measureText(text, 0, text.length()); // 得到text的宽度 int line = (int) Math.ceil(textWidth / viewWidth) + 1; //得到行数 if(!hasDrawed) { //通过行数设置view的高度,最后加的1/2行高是为了把p、j这种跨行的字母显示完整 this.setLayoutParams(new LayoutParams(viewWidth, textSize * line + textSize / 2)); } if (textWidth < viewWidth) { canvas.drawText(text, 0, textSize, paint); } else { int currIndex = 0; int lineNum = 1; String lastLine = ""; lines = new ArrayList<String>(); int lineWords = (int) ((float)text.length() / ((float) textWidth / (float) viewWidth + 2)); for (int i = lineWords; i < text.length(); i++) { String subStr = text.substring(currIndex, i); int width = (int) paint.measureText(subStr, 0, subStr.length()); if (width < viewWidth) { lastLine = subStr; if (i == text.length() - 1) { lastLine = text.substring(currIndex, ++i); canvas.drawText(lastLine, 0, lineNum * textSize, paint); lines.add(lastLine); } continue; } else { canvas.drawText(lastLine, 0, lineNum * textSize, paint); lines.add(lastLine); currIndex = i - 1; lineNum++; i--; if(i + lineWords < text.length()) i += lineWords; } } hasDrawed = true; } } } public String getText() { return text; } public void setText(String text) { this.text = text; hasDrawed = false; invalidate(); } }