Reputation: 1322
So I have a menu that pops up when a button is clicked. In that menu, user can enter "Assignment Name" which can be a String, and "Grade" and "Max Points Available" which will be numbers.
Now I want to make sure that User doesn't enter nothing or null
in any of those EditText fields. So is there a way to disable the OK
button until valid input is entered. Below is a picture of what the pop-up looks like.
Below is my code in MainActivity
Button add = (Button)findViewById(R.id.addBtn);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.add_individual_name, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setView(promptsView);
final EditText assignmentName = (EditText) promptsView.findViewById(R.id.enteredIndividualName);
final EditText gradeReceived = (EditText) promptsView.findViewById(R.id.enteredUserGrade);
final EditText maxPoints = (EditText) promptsView.findViewById(R.id.enteredMaxPoints);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String name = assignmentName.getText().toString();
String grade = gradeReceived.getText().toString();
String totalPossible = maxPoints.getText().toString();
checkIfNameAlreadyExists(name);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}});
Also, I want to disable the "OK" button if the "Assignment Name" already exists in my Database. I have a function that checks if item exits in DB.
Let me know if you want to see the code for XML of AlertDialog
or anything else.
Thanks
Upvotes: 2
Views: 449
Reputation: 60923
You should add the TextWatcher
for your EditText
. And in afterTextChanged, simply check the condition for enable/disable OK button
// Your alert dialog config
...
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
// disable the button as default start
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
// add TextWatcher for EditText
editTextAssignmentName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if (s.length() >= 1) { // add your condition here, in your case it is checkIfNameAlreadyExists
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
} else {
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
}
});
Upvotes: 2