如何从AlertDialog返回值

时间:2019-01-02 15:29:25

标签: java alertdialog

所以我使用带有两个按钮的AlertDialog();单击后,AlertDialog应该返回一个值。 我写了下面的代码,但我不明白AlertDialog的行为。  这是我的代码:

我的函数TransactionAccDialog()应该返回true或false,这取决于用户的选择(单击按钮)。 根据返回值,将执行其他操作。

private boolean TransactionAccDialog() {

        final boolean[] answer = new boolean[1];
        getActivity().runOnUiThread(new Runnable() {
            @Override
          public void run() {
 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("Information");
                builder.setMessage("Transaction accéptée");
                builder.setPositiveButton(" Confirmer ", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i("lamyae", "input" + input);

                                answer[0]=true;

                        dialog.dismiss();
                    }
                });
                builder.setNeutralButton(" Annuler ", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        answer[0]=false;
                        dialog.dismiss();


                    }
                });
                 AlertDialog dialog = builder.create();
                 dialog.show();
                 Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                 Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
                 positiveButton.setTextColor(Color.parseColor("#FFFFFFFF"));
                 positiveButton.setBackgroundColor(Color.parseColor("#FF00FF00"));
                 negativeButton.setTextColor(Color.parseColor("#FFFFFFFF"));
                 negativeButton.setBackgroundColor(Color.parseColor("#FFFF0000"));
            }
});

        return answer[0];
    }



//The return values are used as follow in the same Fragment as the alertdialog:


public void user(){
 if(TransactionAccDialog()==true){
                             ImpresssionDialog();
                             ImpressionTicket();
                        }
                        else {
                            try {
                                getActivity().finish();
                                Intent intent = new Intent(getActivity(), CashActivity1.class);
                                startActivity(intent);

                            } catch (Throwable throwable) {
                                throwable.printStackTrace();
                            }
                        }

}

我希望Alertdialog等待操作,然后继续。但是事实并非如此。它直接执行“ else {}”代码。

有人可以帮忙吗?我需要一种方法来等待对按钮之一的操作完成。

谢谢。

0 个答案:

没有答案
相关问题