之前一直在找 textview 有没有方法获取最后一个字符的位置,
eoe里有个大神提出有getSecondaryHorizontal()这个方法可以获取到某个字符的位置 (http://www.eoeandroid.com/thread-317366-1-1.html);
于是就照着这个思路往下做,判断离右侧的距离,如果不够的话,放到下一行。
不过实测发现,这个方法获取的位置是不准的(汗,不知道为啥),于是就一直找怎么获取textview的最后一个字符的位置,但是网上内容有很少,找不到,耽误了好久。
后来根据网上已有的 "整齐排版textview"的启发,觉得还不如自己去画文字。最后终于解决了,代码如下:
public class MyTextView extends TextView {
private float LineSpacing = 1.6f;//行与行的间距
private Paint paint1 = new Paint();
private Paint paint2 = new Paint();
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
paint1.setTextSize(App.Dp2Px(context, 14));
paint1.setColor(Color.parseColor("#8b8b8b"));
paint1.setAntiAlias(true);
paint2.setTextSize(App.Dp2Px(context, 12));
paint2.setColor(Color.parseColor("#9cc813"));
paint2.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
int textShowWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
int lineCount = 0;
String text = getText().toString();
float textSize = paint1.getTextSize();
if (text == null) return;
char[] textCharArray = text.toCharArray();
int length = textCharArray.length;
float drawedWidth = 0;
float charWidth;
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;
}
canvas.drawText(textCharArray, i, 1, drawedWidth, (lineCount + 1) * textSize * LineSpacing, paint1);
drawedWidth += charWidth;
}
String appendText = "(多选)";
float addTextLength = paint2.measureText(appendText);
if (textShowWidth - addTextLength < drawedWidth) {
lineCount++;
canvas.drawText(appendText, 0, (lineCount + 1) * textSize * LineSpacing, paint2);
} else {
canvas.drawText(appendText, drawedWidth, (lineCount + 1) * textSize * LineSpacing, paint2);
}
setHeight((int) ((lineCount + 1) * (int) textSize * LineSpacing + 10));
}
}