解決了什麼問題?
1、EditText設置Maxlines無效,還是會折行
2、TextView設置Maxlines和ellipsize不生效
問題描述
我們在使用EditText的時候,如果用戶輸入太長就會折行,我們希望設置行數來限制用戶的輸入,於是設置maxlines參數爲1,但是當用戶輸入超過1行時還會折行,現在就來看看原因和解決方法。
使用TextView希望只顯示一行,然後超出的部分打點,設置Maxlines和ellipsize=“end”,TextView只顯示了一行,但是沒有打點。
Maxlines是怎麼做的和singleLine有什麼區別?
EditText是繼承TextView實現的,所以我們先看看兩個方法直接有什麼區別。
android:maxLines Makes the TextView be at most this many lines tall.
android:singleLine Constrains the text to a single horizontally scrolling line instead of letting it wrap onto multiple lines, and advances focus instead of inserting a newline when you press the enter key.
可以看出,maxLines 是在限制高度, singleLine 是強制不讓換行。具體效果有什麼區別呢? 從高度來講是一樣的,兩者肯定都顯示一行,但從換行的位置來講就有區別了,maxLines並不會改變其換行的位置,而singleLine則會。如果超過一行singleLine會在一行內顯示,ellipsize爲end後面加上"…",而maxlines=“1” 則不會,它依然會在原來換行的位置換行,所以有時候一行不滿,但是卻不顯示剩下的部分。
解決方法及原理
1、EditText設置Maxlines無效,還是會折行
解決方法1:
通過以上的分析,顯而易見,我們可以通過設置singleline爲true就可以讓EditText不折行。
解決方法2:
設置EditText的InputType。爲什麼設置inputType就會正常呢?我們需要看一段代碼。
public void setInputType(int type) {
...
boolean singleLine = !isMultilineInputType(type);
// We need to update the single line mode if it has changed or we
// were previously in password mode.
if (mSingleLine != singleLine || forceUpdate) {
// Change single line mode, but only change the transformation if
// we are not in password mode.
applySingleLine(singleLine, !isPassword, true);
}
...
}
當我們設置inputType的時候回調用applySingleLine方法
private void applySingleLine(boolean singleLine, boolean applyTransformation,
boolean changeMaxLines) {
mSingleLine = singleLine;
if (singleLine) {
setLines(1);
setHorizontallyScrolling(true);
if (applyTransformation) {
setTransformationMethod(SingleLineTransformationMethod.getInstance());
}
} else {
if (changeMaxLines) {
setMaxLines(Integer.MAX_VALUE);
}
setHorizontallyScrolling(false);
if (applyTransformation) {
setTransformationMethod(null);
}
}
}
然後調用設置橫向滾動等信息,最後調用setTransformationMethod方法
public final void setTransformationMethod(TransformationMethod method) {
if (method == mTransformation) {
// Avoid the setText() below if the transformation is
// the same.
return;
}
if (mTransformation != null) {
if (mSpannable != null) {
mSpannable.removeSpan(mTransformation);
}
}
...
setText(mText);
...
}
mSpannable.removeSpan(mTransformation);這個方法移除了TextView的內部折行等信息,所以當我們設置了inputType的時候,也不會出現問題。
2、TextView設置Maxlines和ellipsize不生效
解決方法1:
通過以上的分析,顯而易見,我們可以通過設置singleline爲true就可以讓TextView不折行,進而出現我們需要的打點效果。
需要注意的是,一般情況下設置Maxlines和ellipsize在渲染時是不會出現不生效的問題的。