当用户尝试插入超过最大限制的文本时如何进行吐司?

时间:2011-10-31 12:03:05

标签: java android android-edittext toast textwatcher

当用户尝试插入超过最大限制的文字时,如何弹出Toast

<EditText
    android:maxLength="28"
    ...
 />

我尝试使用TextWatcher,但它无法正常运行:

public class MyActivity extends Activity implements TextWatcher
{

    // ...

    @Override
    public void afterTextChanged(Editable arg0){}

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3){}

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
    {
        if(etUsername.isFocused() && etUsername.getText().length() == 28)
            Toast.makeText(MyActivity.this, "The username must be at most 28 characters!" , Toast.LENGTH_SHORT).show();
        else if(etPassword.isFocused() && etPassword.getText().length() == 10)
            Toast.makeText(MyActivity.this, "The password must be at most 10 characters!" , Toast.LENGTH_SHORT).show();
    }
}

修改

我还尝试将代码放在afterTextChangedbeforeTextChanged中,但它无法解决问题。

EDIT2:

我想要的是Toast只有EditText中有28个字符并且用户正在尝试添加第29个字符时才能弹出Toast。只有当TextEdit中有27个字符且用户插入第28个字符时,才会弹出上面代码中的{{1}}。

4 个答案:

答案 0 :(得分:3)

实现所需功能的唯一方法是将android:maxLength更改为desiredMaxLength + 1并检查afterTextChanged()中的长度。当length == desiredMaxLength + 1(即操纵s中的afterTextChanged(Editable s)参数)时,您必须手动删除最后一个字符。请注意不要让自己陷入无限循环,因为更改s afterTextChanged()后会再次调用。

答案 1 :(得分:2)

此解决方案适用于我的案例:

    @Override
    public void afterTextChanged(Editable s) {
        if(etUsername.isFocused() && etUsername.getText().toString().trim().length() > MAX_CHARS){
        etUsername.setText(s.toString().substring(0, MAX_CHARS));
        etUsername.setSelection(s.length()-1);
            Toast.makeText(getActivity(), "Maximum number of characters reached.", Toast.LENGTH_SHORT).show();
        }
    }

希望它有所帮助。

答案 2 :(得分:0)

而不是:

if(etUsername.isFocused() && etUsername.getText().length() == 28)

使用此:

 if(arg0.length() > 28)
      {
String temp=arg0.subString(0,27)
etUsername.setText(temp);
 //Toast come's here
       }

答案 3 :(得分:0)

完整代码如下。它工作得很好。

String tempReview;
EditText et_userReview;
TextView tv_charactersRemaining;

Public void afterTextChanged(Editable s){

if(s.toString().length() <= 200) {
                 tv_charactersRemaining.setText(200 -   s.toString().length()+ " characters remaining");
                 tempReview = s.toString();
                 } else {
                 et_userReview.setText(tempReview);
                 Editable etext = et_userReview.getText();
                 Selection.setSelection(etext, 200);    
Toast.makeText(getApplicationContext(),  "No more characters You have reached the limit.", Toast.LENGTH_SHORT).show();
                 }

}