Android Confirmation dialog returning true or false

前端 未结 8 1270
不知归路
不知归路 2020-12-09 05:40

It seems to be there is no easy way to get an Alert dialog to return a simple value.
This code does not work (the answer variable cannot be set

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 05:50

    I was also struggling to use a blocking confirm dialog and I finally did it using a BlockingQueue :

    public static class BlockingConfirmDialog{
    
        private Activity context;
    
        BlockingQueue blockingQueue;
    
        public BlockingConfirmDialog(Activity activity) {
            super();
            this.context = activity;
            blockingQueue = new ArrayBlockingQueue(1);
        }
    
        public boolean confirm(final String title, final String message){
    
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new AlertDialog.Builder(context)
                    .setTitle(title)
                    .setMessage(message)
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) { 
                            blockingQueue.add(true);
                        }
                     })
                     .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            blockingQueue.add(false);
                        }
                    })
                     .show();
                }
            });
    
            try {
                return blockingQueue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
                return false;
            }
    
        }
    }
    

提交回复
热议问题