【问题标题】:Android - Checking if editText is >3 before and after user inputAndroid - 在用户输入之前和之后检查editText是否> 3
【发布时间】:2014-01-16 15:51:03
【问题描述】:

我有一些代码,如果 editText 字段中的字符少于 3 个,我需要禁用“创建帐户”按钮。如果用户输入 3 个字符,则该按钮应启用自身以便可以使用。

我已经构建了 if else 语句,如果 editText 字段中的字符少于 3 个,则禁用按钮,但是在输入时,当用户插入 3 个字符时,它不会重新评估该语句是否为真所以按钮当然会保持禁用状态。

一旦用户在编辑文本字段中输入 3 个字符,按钮应该会自行启用。

    Button buttonGenerate = (Button) findViewById(R.id.btnOpenAccountCreate);
    userInitials = (EditText) findViewById(R.id.etUserChar);
    if (userInitials.getText().toString().length() > 3) {
                // Account Generator Button
                            buttonGenerate.setEnabled(true); // enable button;
                            buttonGenerate.setOnClickListener(new OnClickListener() { 
//Do cool stuff here
                                @Override
                                public void onClick(View v) {

                                }
                            });// END BUTTON
            } else {

                // If UserInitials is empty, disable button
                            Toast.makeText(this, "Please enter three(3) characters in the Initials Field ", Toast.LENGTH_LONG)
                                    .show();
                            buttonGenerate.setEnabled(false); // disable button;
            }// END IF ELSE

【问题讨论】:

    标签: java android button android-edittext


    【解决方案1】:

    您想使用TextWatcher

    每当您的EditText 中包含listener 的文本发生更改时,都会触发此事件。您只需将 listener 附加到您的 EditText 就像您将任何其他 listener 一样,然后覆盖其方法,并从下面的链接示例中检查长度

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

    然后您不需要签入onClick(),只需默认禁用Button,如果满足条件则启用onTextChanged()

    重写

    上面可以清理为

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

    我也将其更改为> 2,因为我认为这实际上是您想要的,但您拥有它的方式有点令人困惑。您说“输入三(3)”,这听起来正好是 3,但您的代码看起来不同。无论如何,这对你来说很容易改变。

    See this answer for an example

    【讨论】:

    • 出色的工作。经过一些工作,我根据您的回答弄清楚了。非常感谢您的宝贵时间。
    • 你不是说s.length() > 2吗?
    • 另外,? true : false 是多余的
    • @YoungCoconutCode 是的,你是对的。谢谢,我已经对其进行了编辑以反映这一点。
    【解决方案2】:

    对 EditText 使用 onTextChangedListener 来检查值并禁用或启用按钮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多