Search code examples
androidandroid-alertdialogandroid-dialogfragmentdialogfragment

Set positive and negative buttons both in the same line in an Alert Dialog fragment


For API 16 the positive and negative buttons come one below the other. While in API 19 and above they come in the same line. Changing the font does not change the position. How can I get both the buttons to be in the same line?

enter image description here

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.resume_session)
            .setMessage(R.string.session_question)
            .setPositiveButton(R.string.continue_session, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    setDataAndStart(dataHelper, exDB);
                }
            })
            .setNegativeButton(R.string.restart_session, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    exDB.resetCurrentWorkoutRecords();
                    setDataAndStart(dataHelper, exDB);
                }
            });
    final AlertDialog pendingWorkoutAlert = builder.create();
    //check for dp size of the phone and then change font
    if (AppApplication.displayType.equals("normal")) {
        pendingWorkoutAlert.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Button btnPositive = pendingWorkoutAlert.getButton(Dialog.BUTTON_POSITIVE);
                btnPositive.setTextSize(14);

                Button btnNegative = pendingWorkoutAlert.getButton(Dialog.BUTTON_NEGATIVE);
                btnNegative.setTextSize(14);
            }
        });
    }
    return pendingWorkoutAlert;

Solution

  • The problem is that you are not specifying your own layout and thus Android uses the default one, so that you can't influence how the content of your dialog is wrapped.

    You can use AlertDialog.Builder#setView to define your own layout.