Enable and disable Button according to the text in EditText in Android

后端 未结 3 1035
盖世英雄少女心
盖世英雄少女心 2020-12-17 14:59

I want to disable by Button if the words in the EditText is less than 3 words, and if the words in the EditText are more than 3 words then I want to enable it so that it can

3条回答
  •  有刺的猬
    2020-12-17 15:20

    The problem with using afterTextChanged alone is at application start it can't disable the button initially until you start typing to your EditText.

    This is how I implemented mine and it works great. Call this method inside your Activity's onCreate method

    void watcher(final EditText message_body,final Button Send)
    {
        final TextView txt = (TextView) findViewById(R.id.txtCounter);
        message_body.addTextChangedListener(new TextWatcher()
        {
            public void afterTextChanged(Editable s) 
            { 
                txt.setText(message_body.length() + " / 160"); //This is my textwatcher to update character left in my EditText
                if(message_body.length() == 0)
                    Send.setEnabled(false); //disable send button if no text entered 
                else
                    Send.setEnabled(true);  //otherwise enable
    
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after){
            }
            public void onTextChanged(CharSequence s, int start, int before, int count){
            }
        }); 
        if(message_body.length() == 0) Send.setEnabled(false);//disable at app start
    }  
    

提交回复
热议问题