【发布时间】:2019-09-19 02:56:49
【问题描述】:
我试图通过限制新行和字符的数量来限制用户过度填充 UI。
我正在使用下面的代码,但问题是getLineCount() 似乎只获得了\n 计数而不是行计数。因此,如果有没有\n 字符的新行,用户仍然可以过度填充。
因此,如果用户输入 3 行文本,然后他仍然可以添加 5 行新行,那么他可能会弄乱他和其他人的 UI。那么我该如何修复这个错误呢?
注意:我已经尝试过 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字段上使用正则表达式设置过滤器
-
@Kavita_p 您能否发布正则表达式作为答案。
-
请尝试以下正则表达式来限制行数,您可以将其用作过滤器regex101.com/r/fuBP8I/1
标签: android user-interface android-edittext