Нам это нужно для того, чтобы запретить пользователю вводить нулевые значения в качестве имен файлов. Кнопка сохранения должна быть отключена, если userInput не равен нулю.
Вот текущий код:
public void openDialog() {
@SuppressLint("InflateParams") View view = (LayoutInflater.from(AudioRecorder.this)).inflate(R.layout.audio_name_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(AudioRecorder.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true);
alertBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
Toast.makeText(AudioRecorder.this, "Next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
filePathMaking();
}
});
alertBuilder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
}




Вы можете сделать что-то вроде этого:
if (input != null){
button.setEnabled(true); //you can click your button now
}else{
button.setEnabled(false); //you can not click your button
}
Вот пример общего пользовательского диалога:
Это будет ваш диалоговый класс (или что-то подобное, это только пример):
public class FullSizeImageDialog extends Dialog {
private ImageView imageView;
private ProgressBar fullImageProgreesBar;
private Context dialogContext;
public FullSizeImageDialog(@NonNull Context context) {
super(context);
setContentView(R.layout.full_size_image_dialog);
dialogContext = context;
imageView = findViewById(R.id.full_size_image);
fullImageProgreesBar = findViewById(R.id.fullImageProgreesBar);
}
}
А это ваш макет для диалога (R.id.full_size_image в моем случае):
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:background = "#66F9B639">
<!--Place your views here-->
</android.support.constraint.ConstraintLayout>
И когда вы хотите показать свой диалог, это очень просто:
FullSizeImageDialog dialog = new FullSizeImageDialog ();
dialog.show();
И теперь вы можете поместить свою логику в свой собственный диалоговый класс.
Я бы создал собственный диалоговый класс для обработки всего, что там есть, я отредактирую свой ответ
Я отредактировал свой ответ, обратите внимание, что для этой простой задачи вы можете использовать TextChangedListener, как в приведенных выше ответах, но я хотел показать вам более чистое решение для более сложных задач.
Вам нужно добавить слушателя к тексту редактирования элемента ввода
AlertDialog.Builder builder = new AlertDialog.Builder(AudioRecorder.this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("Record Sound");
builder.setMessage("Enter Username");
builder.setPositiveButton("PositiveButton",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// DO TASK
}
});
builder.setNegativeButton("NegativeButton",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// DO TASK
}
});
// Set `EditText` to `dialog`. You can add `EditText` from `xml` too.
final EditText userInput = new EditText(AudioRecorder.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
input.setLayoutParams(lp);
builder.setView(input);
final AlertDialog dialog = builder.create();
dialog.show();
// Initially disable the button
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
// OR you can use here setOnShowListener to disable button at first time.
// Now set the textchange listener for edittext
input.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
// Check if edittext is empty
if (TextUtils.isEmpty(s)) {
// Disable ok button
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
} else {
// Something into edit text. Enable the button.
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
}
});
В методе изменения текста проверьте, больше ли длина нуля, и назначьте там свойство кнопки
Добавьте TextChangedListener в текст редактирования. Сделайте кнопку включенной или отключенной с помощью пользовательского ввода.
Вы можете получить доступ к положительной кнопке как dialog.getButton(AlertDialog.BUTTON1).setEnabled(false); и
Как отключить .setPositiveButton("Сохранить")? это не обычная кнопка.