Search code examples
androidandroid-layoutandroid-activitydialogandroid-dialog

Android: How Can I put a Dialog box in a loop


I am trying to make activity screen in which agreement will be displayed in a dialogue box. How can I make the dialog box repeat itself each time user presses "cancel" or "Disagree". And continue activity on agree. ?


Solution

  • I would agree that providing the option to "cancel" or "no" while providing no other option but to accept, you could possibly achieve it, using the View's method callOnClick.

    This will allow you to trigger the dialog each time the user clicks on No or Cancel. However this would only work with the assumption that you are triggering the original Dialog from a Button since you haven't provided any code to look at (Your activity, its xml layout):

    public class MainActivity extends AppCompatActivity {
    final Context context = this;
    private Button button;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.a_main_btn);
    
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View view = v;
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                alertDialogBuilder.setTitle("Dialog Title");
                alertDialogBuilder
                        .setMessage("Click yes to exit dialog")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MainActivity.this.finish();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                view.callOnClick();
                            }
                        });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });
    }