gpt4 book ai didi

java - 当 EditText 为空时防止 AlertDialog 关闭

转载 作者:行者123 更新时间:2023-12-02 13:17:32 25 4
gpt4 key购买 nike

因此,无需创建自定义对话框,因为我目前有许多对话框布局,并且不想为每个对话框都创建自定义对话框,有没有一种方法可以防止在按下肯定按钮时关闭此对话框EditText 是空的?

目前,每次我按 Enter 键时它都会关闭对话框,并且 EditText 字段中没有任何内容。

public AlertDialog webpageDialog() {
AlertDialog.Builder webpageDialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
webpageDialogBuilder.setView(inflater.inflate(R.layout.dialog_webpage, null))
.setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog webpageDialog = webpageDialogBuilder.create();

webpageDialog.setButton(DialogInterface.BUTTON_POSITIVE, context.getString(R.string.enter), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
EditText webpageInput = (EditText) webpageDialog.findViewById(R.id.dw_et_webpage_address);
Log.d(TAG, "Positive on click");
if(TextUtils.isEmpty(webpageInput.getText().toString())){
Log.d(TAG, "Edit text empty");
webpageInput.setError(context.getString(R.string.error_web_required));
} else {
Log.d(TAG, "Edit text not empty");
ms.setUriString("http://" + webpageInput.getText().toString());
ms.returnWithResult(1);
dialog.cancel();
}
Log.d(TAG, "Returning");
}
});
Log.d(TAG, "Returning dialog");
return webpageDialog;
}

最佳答案

我就是这么做的。

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);

EditText yourEditText = new EditText(this);
layout.addView(yourEditText);

builder.setView(layout);

// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

final AlertDialog dialog = builder.create();

dialog.show();

dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

if ("".equals(yourEditText.getText().toString().trim())) {
//this will stop your dialog from closing
yourEditText.setError("This field is required!");
return;

}

//you logic here


dialog.dismiss();

}
});

关于java - 当 EditText 为空时防止 AlertDialog 关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43707978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com