[英]Android Set New Line And Length Limit To EditText
我試圖通過限制新行和字符的數量來限制用戶過度填充UI。
我正在使用下面的代碼,但問題是getLineCount()
似乎只獲得\\n
計數而不是行數。 因此,如果沒有\\n
字符的新行,用戶仍然可以溢出。
因此,如果用戶輸入3行文本,然后他仍然可以添加5行新行,他可以搞砸他和其他UI。 那么我該如何修復這個bug呢?
注意:我嘗試過XML行限制屬性,但它不起作用: android:maxLines="5"
etDescription.addTextChangedListener(new TextWatcher()
{
boolean _ignore = false; // indicates if the change was made by the TextWatcher itself.
final int DESCRIPTION_LETTER_LIMIT = 168;
final int DESCRIPTION_LINE_LIMIT = 5;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
if(after > DESCRIPTION_LETTER_LIMIT || etDescription.getLineCount() > DESCRIPTION_LINE_LIMIT )
{
Log.d(TAG, "beforeTextChanged: limit reached. After count and line count: "+ after+ " | "+etDescription.getLineCount());
isLimitReached = true;
}
else
{
Log.d(TAG, "beforeTextChanged: limit NOT reached. After count and line count: "+ after+ " | "+etDescription.getLineCount());
isLimitReached = false;
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
@Override
public void afterTextChanged(Editable s)
{
if (_ignore)
return;
_ignore = true; // prevent infinite loop
// Change your text here.
if(isLimitReached)
{
if(etDescription.getSelectionEnd() - 1 != -1)
{
etDescription.getText().delete(etDescription.getSelectionEnd() - 1, etDescription.getSelectionStart());
isLimitReached = false;
}
}
_ignore = false; // release, so the TextWatcher start to listen again.
}
});
試試這個吧
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:lines="1"/>
或者您也可以在代碼中執行此操作
EditText editText = findViewById(R.id.editText);
editText.setLines(1);
你可以在這里閱讀更多關於doc的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.