在项目开发中有些需求和在开发中的习惯不一样,比如我们遇到的TextView在设置了文本之后出现不该换行的时候换行的问题。
网上搜索了下大概有那么几种办法,小菜也试了几个,发现有的不显示,有的达不到效果,后来想了想重新写TextView应该可以解决问题。
废话不多说,看下边代码。
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
View view = (View) this.getParent();
textShowWidth = view.getMeasuredWidth() - paddingLeft - paddingRight
- marginLeft - marginRight;
int lineCount = 0;
text = this.getText().toString();// .replaceAll("\n", "\r\n");
if (text == null)
return;
char[] textCharArray = text.toCharArray();
// 已绘的宽度
float drawedWidth = 0;
float charWidth;
for (int i = 0; i < textCharArray.length; i++) {
charWidth = paint1.measureText(textCharArray, i, 1);
if (textCharArray[i] == '\n') {
lineCount++;
drawedWidth = 0;
continue;
}
if (textShowWidth - drawedWidth < charWidth) {
lineCount++;
drawedWidth = 0;
}
boolean color = false;
try {
color = isColor(i);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (color) {
canvas.drawText(textCharArray, i, 1, paddingLeft + drawedWidth,
(lineCount + 1) * textSize * LineSpacing, paintColor);
} else {
canvas.drawText(textCharArray, i, 1, paddingLeft + drawedWidth,
(lineCount + 1) * textSize * LineSpacing, paint1);
}
if (textCharArray[i] > 127 && textCharArray[i] != '、'
&& textCharArray[i] != ',' && textCharArray[i] != '。'
&& textCharArray[i] != ':' && textCharArray[i] != '!') {
drawedWidth += charWidth + Spacing;
} else {
drawedWidth += charWidth;
}
}
setHeight((int) ((lineCount + 1) * (int) textSize * LineSpacing + 10));
}
然后。。。。。。。。就好了。
还有一种办法是用edittext 设置enable=false;好像也可以,没验证过,编辑的时候偶尔发现。
资源代码全部已经上传,请转至:http://download.csdn.net/detail/xiaohu415034622/9393731
谢谢.希望能帮到你,不喜勿喷。