以下为解决排版核心代码
public class MyTextView extends TextView {
private String text;
private float textSize;
private float paddingLeft;
private float paddingRight;
private float paddingTop;
private float paddingBottom;
private int textColor;
private Paint paint1 = new Paint();
private float textShowWidth;
private int lineSpace;//行间距
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
text = this.getText().toString();
textSize = this.getTextSize();
textColor = getResources().getColor(R.color.color_black_333333);
paddingLeft = this.getPaddingLeft();
paddingRight = this.getPaddingRight();
paddingTop = this.getPaddingTop();
paddingBottom = this.getPaddingBottom();
lineSpace = (int) paddingTop/2;
paint1.setTextSize(textSize);
paint1.setColor(textColor);
paint1.setAntiAlias(true);
}
/**
* 设置画笔颜色
* @param color
*/
public void setPaintColor(int color){
paint1.setColor(color);
}
@Override
public void onDraw(Canvas canvas) {
textShowWidth = this.getMeasuredWidth() - paddingLeft - paddingRight;
int lineCount = 0;
text = this.getText().toString();
if (text == null)
return;
char[] textCharArray = text.toCharArray();
float drawedWidth = 0;
float charWidth;
int length =textCharArray.length;
float space=0;
for (int i = 0; i < length; i++) {
charWidth = paint1.measureText(textCharArray, i, 1);
if (textCharArray[i] == '\n') {
lineCount++;
drawedWidth = 0;
continue;
}
if (textShowWidth - drawedWidth < charWidth) {
lineCount++;
drawedWidth = 0;
}
//调整行间距
if(lineCount==0){
space = paddingTop;
}else {
space = paddingTop+(lineCount+1)*lineSpace;
}
canvas.drawText(textCharArray, i, 1, paddingLeft + drawedWidth,
(lineCount + 1) * textSize+ space, paint1);
drawedWidth += charWidth;
}
//修正高度
setHeight((lineCount + 1) * ((int) textSize) +(int) (paddingTop+paddingBottom+(lineCount+1)*lineSpace));
}
}
不做过多的阐述,添加了行间距的设置,下图长篇的内容区域则为效果