开发者

How do you gray out a "Submit" button when specific EditText boxes are empty?

开发者 https://www.devze.com 2023-03-03 12:50 出处:网络
Regarding an Android app I am creating: I have three EditText boxes that need to be filled with numbers/strings. I have a submit button that will start a series of calculations.

Regarding an Android app I am creating:

I have three EditText boxes that need to be filled with numbers/strings. I have a submit button that will start a series of calculations.

IF any box is empty and submit is pressed, the app crashes. I have tried to do this with try-catch statement, but it is not working out. I simply want to disable the button until three boxes have numb开发者_开发百科ers. I know there is a way to setEnabled(false) I think? Or is there a better way? Will this grey out the button? Or is that an unrelated function to setEnabled?


Try this solution.

EditText edit1;
EditText edit2;
EditText edit3;
View button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Your initialization code...

    TextWatcher watcher = new LocalTextWatcher();
    edit1.addTextChangedListener(watcher);
    edit2.addTextChangedListener(watcher);
    edit3.addTextChangedListener(watcher);
    updateButtonState();
}

void updateButtonState() {
    boolean enabled = checkEditText(edit1)
        && checkEditText(edit2)
        && checkEditText(edit3);
    button.setEnabled(enabled);
}

private boolean checkEditText(EditText edit) {
    return Integer.getInteger(edit.getText().toString()) != null;
}

private class LocalTextWatcher implements TextWatcher {
    public void afterTextChanged(Editable s) {
        updateButtonState();
    }

    void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    void onTextChanged(CharSequence s, int start, int before, int count) {
    }
}


You should disable the button by default in the XML so that the user cannot hit the button by accident. After this you need to look at your fields and insure all of them have data before the submission.

You could do this, or you could just have submit run a quick check on all the fields and insure none of them are equal to "".

Basically look like this (If you want to ignore hiding the button and just handle processing after the check)

if (!((t1.getText().toString.compareTo("") == 0) && (t2.getText().toString.compareTo("")==0) ...))
{
Do stuff
}

else
{
Toast message here
}

Otherwise you can just have a "watcher" like the above poster mentioned.


You can also use this check

boolean checkEditText(EditText editText) {
    return editText.getText().toString().trim().equals("");
}


Hi i have tried above code and changed the function to given below for it to work.

private boolean checkEditText(EditText edit) {
    return ((edit.getText().toString()).length() >0 );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消