align AlertDialog buttons to center

前端 未结 9 1862
无人共我
无人共我 2020-12-06 09:09

I use this codes for Android (Java) programming:

public static MessageBoxResult showOk(
        Context context, String title, String message, String okMessa         


        
相关标签:
9条回答
  • 2020-12-06 09:58

    This worked for me :

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(message);
    
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
    
            }
        });
    
    
        final AlertDialog dialog = builder.create();
        dialog.show(); //show() should be called before dialog.getButton().
    
    
        final Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        LinearLayout.LayoutParams positiveButtonLL = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
        positiveButtonLL.gravity = Gravity.CENTER;
        positiveButton.setLayoutParams(positiveButtonLL);
    
    0 讨论(0)
  • 2020-12-06 10:07

    Use crtn's method, but instead of changing the LayoutParam's gravity, change its width to ViewGroup.LayoutParams.MATCH_PARENT;

    0 讨论(0)
  • 2020-12-06 10:08

    You can set the positive, negative and neutral buttons, hide both the positive and neutral buttons, and put the negative button where the neutral button is supposed to be(center) by using LayoutParams.

    in onCreateView:

    dialog = builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
    
                }
            })
                     .setPositiveButton(R.string.go_on, new DialogInterface.OnClickListener() {
                         @Override
                         public void onClick(DialogInterface dialog, int which) {
    
                         }
                     })
                     .setNeutralButton(R.string.do_nothing, new DialogInterface.OnClickListener() {
                         @Override
                         public void onClick(DialogInterface dialog, int which) {
    
                         }
                     })
                     .create();
    

    in onStart():

     super.onStart();
    
        final Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
       positiveButton.setVisibility(View.INVISIBLE);
       final Button neutralButton = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
       neutralButton.setVisibility(View.INVISIBLE);
       final Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
       negativeButton.setLayoutParams(neutralButton.getLayoutParams());
    
    0 讨论(0)
提交回复
热议问题