我试图通过限制新行和新字符的数量来限制用户过度填充UI。
我正在使用下面的代码,但是问题是getLineCount()
似乎只得到\n
而不是行数。因此,如果有一行没有\n
字符的行,用户仍然可以过量填充。
因此,如果用户输入3行文本,然后他仍然可以添加5行,他就可以弄乱自己和其他用户界面。那我该如何解决这个错误呢?
注意:我已经尝试过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.
}
});
答案 0 :(得分:0)
尝试这个
<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);
您可以在文档here上阅读更多内容。