Android - Checking if editText is >3 before and after user input

会有一股神秘感。 提交于 2019-11-29 16:10:34
codeMagic

You want to use a TextWatcher

This will be triggered each time the text in your EditText which has this listener on it has changed. You just attach the listener to your EditText like you would any other listener then override its methods and , from the linked example below, check the length

 @Override
public void onTextChanged(CharSequence s, int start, int before, int count) 
{   
     if (s.length() > 2) 
     {
         buttonGenerate.setEnabled(true);
     }
     else
    {
         buttonGenerate.setEnabled(true);
    }
}

You don't need to check in your onClick() then, just disable the Button by default and enable in your onTextChanged() if the condition is met.

Rewritten

The above could be cleaned up as

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {   
     buttonGenerate.setEnabled((s.length() > 2));
}

I also have changed it to > 2 because I think that's actually what you want but the way you have it is a little confusing. You say "enter three(3)" which sounds like exactly 3 but your code looks different. Anyway, that's easy enough for you to change.

See this answer for an example

Use an onTextChangedListener for the EditText to check the value and disable or enable the button.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!