android - 使用自定义对话框匹配密码

标签 android dialog

我想使用自定义对话框进行 Pin 身份验证。这是我的代码:

public void fetchUI()
{
    add=(Button)findViewById(R.id.pinButton);

    add.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
            final EditText input = new EditText(MainActivity.this);
            input.setTransformationMethod(PasswordTransformationMethod.getInstance());
            alert.setView(input);
            alert.setTitle("Type Your PIN");
            alert.setIcon(R.drawable.ic_launcher);
            alert.setMessage("Please Type Your PIN  below to Authenticate");

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

                }
            });

            alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.cancel();
                }
            });

           alert.show();
        }
    });
}

现在我想这样做:如果我使用正确的 PIN 单击“确定”,则对话框会消失。否则,如果我单击确定,它不会消失。 我怎样才能做到这一点? 任何帮助将不胜感激。

最佳答案

    final String CORRECT_PIN = "123123"; // Should come from somewhere else than a local variable
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            if (CORRECT_PIN.equals(input.getText().toString()) {
                dialog.dismiss();
            } else {
                input.setError(getString(R.string.error_incorrect_pin));
            }    
        }
    });

编辑:以上代码给出了处理验证的正确方法。但是,为了防止在单击按钮后关闭对话框,您需要在自定义对话框按钮中包含您自己的按钮。

其他可能性:仅当 pin 正确时才启用 OK 按钮。您需要在 EditText 上添加文本更改监听器,并在 onTextChange 方法中执行以下操作:

input.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {               
        alert.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(CORRECT_PIN.equals(input.getText().toString());
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
});

关于android - 使用自定义对话框匹配密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13393487/

相关文章:

android - 如何从 OnActivityResult 更新 RecyclerView 元素

android - android :permisson 中的多个权限

java - 无法解析方法'show(android.support.v4.app.FragmentManager, java.lang.String)

c++ - 如何使 QDialogBu​​ttonBox 不关闭其父 QDialog?

android - 在android listView中过滤搜索

android - 使用 camera2 与已弃用的 Camera - 最佳做法是什么?

android - Parcel.readStringArray() 的参数是什么?

css - 对话框内的 Angular 6 Primeng 确认对话框停用页面

android - 关闭 DialogFragment(不是 Dialog)onTouchOutside

ios - 显示 iOS 位置权限对话框的自定义 View