I need to change positive button's text of an AlertBox
from nothing to OK or Add according to the entered text. I have the following code for the AlertBox
creation and displaying:
public void show() {
View inputView = LinearLayout.inflate(mContext, R.layout.goal_tag_input, null);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setView(inputView);
mInput = inputView.findViewById(R.id.goal_tag_input);
mInput.addTextChangedListener(mTagNameTextWatcher);
List<Tag> availableTags = AppDatabase.getInstance(mContext).tagDao().getAll();
mAvailableTagLabels = new ArrayList<>();
for (Tag tag : availableTags) {
mAvailableTagLabels.add(tag.getName());
}
ArrayAdapter<String> inputAdapter = new ArrayAdapter<>(mContext,
android.R.layout.select_dialog_item, mAvailableTagLabels);
mInput.setAdapter(inputAdapter);
builder.setCancelable(true);
builder.setPositiveButton("", mAddTagClickListener);
builder.setNegativeButton(R.string.Cancel, null);
mDialog = builder.create();
mDialog.show();
}
Also I have a TextWatcher
implementation:
private TextWatcher mTagNameTextWatcher = 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) {
String tagName = mInput.getText().toString();
if (tagName.trim() != "") {
Button buttonPositive = mDialog.getButton(DialogInterface.BUTTON_POSITIVE);
if (mAvailableTagLabels.contains(tagName)) {
buttonPositive.setText(R.string.OK);
} else {
buttonPositive.setText(R.string.Add);
}
}
}
};
During debugging I observed that the text value of the buttonPositive
is changed appropriately, but it is not reflected in the interface. Do you have any ideas why is it so? I checked this answer but it didn't help.