In Android, how to make Login button disable with respect to EditText?

android, android-button, android-edittext, button

Solution

heres what you are looking for :

private EditText et1,et2;
//  create a textWatcher member
private TextWatcher mTextWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        // check Fields For Empty Values
        checkFieldsForEmptyValues();
    }
};

void checkFieldsForEmptyValues(){
    Button b = (Button) findViewById(R.id.button1);

    String s1 = et1.getText().toString();
    String s2 = et2.getText().toString();

    if(s1.equals("")|| s2.equals("")){
        b.setEnabled(false);
    } else {
        b.setEnabled(true);
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_check);
    et1 = (EditText) findViewById(R.id.editText1);
    et2 = (EditText) findViewById(R.id.editText2);


    // set listeners
    et1.addTextChangedListener(mTextWatcher);
    et2.addTextChangedListener(mTextWatcher);

    // run once to disable if empty
    checkFieldsForEmptyValues(); 
}

Problem

If `EditText` is empty then Login `Button` has to be disabled. And if `EditText` has some texts then Login `Button` has to be enabled. Well you can see this method on Instagram Login. Both fields are empty, Sign in `Button` is DISABLED. Here Password field is empty, so still Sign in`Button` is DISABLED. Here both Username and Password field is not empty, So Sign in`Button` is ENABLED. how to achieve these steps?? here is my code and it doesn't work.. ``` EditText et1,et2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_check); et1 = (EditText) findViewById(R.id.editText1); et2 = (EditText) findViewById(R.id.editText2); Button b = (Button) findViewById(R.id.button1); String s1 = et1.getText().toString(); String s2 = et2.getText().toString(); if(s1.equals("")|| s2.equals("")){ b.setEnabled(false); } else { b.setEnabled(true); } } ```

Original source

Related problems