如何从警报对话框中退出事件处理程序?

时间:2015-05-18 15:32:55

标签: java android

因此,有一个警告对话框,用于检查首选项中是否存在值,并且我无法从否定按钮中退出主onClickListener。

Button b = (Button) findViewById(R.id.button4);
b.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        EditText et = (EditText) findViewById(R.id.editText2);
        EditText et2 = (EditText) findViewById(R.id.editText3);

        String code = et.getText().toString();
        String name = et2.getText().toString();
        if (prefs.contains(code)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(Definitions.this);
            builder.setTitle(R.string.error);
            builder.setCancelable(false);
            builder.setMessage(R.string.value_exist);
            builder.setPositiveButton(R.string.positive, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.setNegativeButton(R.string.negative, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //how to get out of the main onClickListener from here?
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }
        editor.putString(code, name);
        editor.apply();
    }
});

1 个答案:

答案 0 :(得分:0)

这里的onClick方法:

builder.setNegativeButton(R.string.negative, new  DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //how to get out of the main onClickListener from here?
            }
        });
主侦听器执行期间不执行

,但仅在您点击否定按钮时执行。

最后两行:

    editor.putString(code, name);
    editor.apply();
当您的警报可见时,

已经执行。

你可以做些什么来解决你的问题:

Button b = (Button) findViewById(R.id.button4);
b.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ...
        if (prefs.contains(code)) {
            ...
            AlertDialog alert = builder.create();
            alert.show();
        }else{
            editor.putString(code, name);
            editor.apply();
        }
    }
});