在項目開發中有些需求和在開發中的習慣不一樣,比如我們遇到的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
謝謝.希望能幫到你,不喜勿噴。