Home » Android » java – check box not displayed inside the popup in android-Exceptionshub

java – check box not displayed inside the popup in android-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am trying to add a popup with a checkbox and if the checkbox is not ticked, it shouldn’t be able to press yes on the popup and better some kind of a error message get appeared inside the popup. My attempt is as follows.

    AlertDialog.Builder builder = new AlertDialog.Builder(EmptyActivity.this);
    builder.setTitle(R.string.app_name);
    builder.setMessage("Confirm for go?");
    final CharSequence[] items = {"Something to check before going "};
    final ArrayList selectedItems=new ArrayList();
    builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            //Here you add or remove the items from the list selectedItems. That list will be the result of the user selection.
            if(isChecked) {
                selectedItems.add(which);
            }
        }
    });

    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
            if(selectedItems.size() == 1) {
                //call going api
            }
            else{
                //show an error msg inside pop up to tick the checkbox and unable to click yes
            }
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();

popup displayed as in the below image.

enter image description here

I couldn’t see the checkbox inside the popup when I run it. So any one knows where I got wrong? And how should I show an error msg inside the pop up to inform the user to tick the checkbox before clicking yes?

How to&Answers:
    private void showDialogue() {

            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
            LayoutInflater inflater = this.getLayoutInflater();
            View dialogView = inflater.inflate(R.layout.custom_dashboard, null);
            dialogBuilder.setView(dialogView);
            final AlertDialog alertDialog = dialogBuilder.create();
            final CheckBox one = dialogView.findViewById(R.id.chk01);

            Button done = dialogView.findViewById(R.id.done);
            done.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (one.isChecked()) {
                  //do something
                }else{
 //do something               
}
            });
            alertDialog.show();


        }