gpt4 book ai didi

android - 从 Android AlertDialog 函数返回 bool 值

转载 作者:行者123 更新时间:2023-11-30 03:06:40 25 4
gpt4 key购买 nike

在我的应用程序中,我有一个功能可以使用输入文本检查显示的 AlertDialog 中输入的文本。如果文本等于字符串变量,则返回 True,否则返回 False,并捕获此结果值以继续条件代码。

但是这似乎有点困难,因为我在其他帖子中看到询问如何解决同样的问题。

我已经这样做了:

private boolean checkAdministratorPassword() {
final enterPasswordResult[0] = false;

AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Confirm action");
alert.setIcon(R.drawable.ic_launcher);
alert.setMessage("Enter administrator pass to continue");

final EditText input = new EditText(mContext);
input.setPadding(5, 0, 5, 0);
alert.setView(input);

alert.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {

String strPass = input.getEditableText().toString();
if (strPass.length() == 0) {
dialog.cancel();
}
if (strPass.equalsIgnoreCase(Constantes.ADMIN_PASS)) {
enterPasswordResult[0] = true;
dialog.cancel();

} else {
Toast.makeText(mContext, "Invalid pass..!!", Toast.LENGTH_LONG).show();
dialog.cancel();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();

return enterPasswordResult[0];
}

我这样调用这个函数:

If ( checkAdministratorPassword() == True ){
//true conditions
}

但问题是检查函数不等待结果继续执行代码,它只是自行继续,我没有得到适当的行为。

最佳答案

问题是您正试图在程序的逻辑流中处理异步事件。如果您将 Dialog 设为自己的类并使用 Interface 回调到您的主机 Activity ,则可以执行此操作。查看有关 DialogFragment 的文档.

public interface PasswordCheckListener{
public void valid(boolean check);
}

private static class PasswordDialog extends DialogFragment {

private PasswordCheckListener listener;

public static PaswordDialog newInstance(PasswordCheckListener listener){
this.listener = listener;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Put your dialog creation code here
}

private checkAdminPassword(){
//Whatever your check passowrd code is
listener.valid(result);
}
}

我知道我没有为您实现所有代码,但这是一般的想法。通过使用接口(interface),您可以在用户输入密码并按下提交时回调到您的主机 ActivityFragment。然后,您可以在事件发生时对其进行处理,而不必在程序流中进行处理。

关于android - 从 Android AlertDialog 函数返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21705948/

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