align AlertDialog buttons to center

前端 未结 9 1884
无人共我
无人共我 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:52

    Tried crtn's method and Scott Brown's modification, both didn't render how I liked.

    crtn's solution didn't change the appearance of the buttons for me at all (I'm using android.R.style.Theme_Material_Light_Dialog) and Scott Brown's solution made my positive button extend past the edge of the dialog parent.

    For Theme_Material_Light_Dialog the buttons are contained within a LinearLayout subclass that uses a blank View as its 2nd (index 1) element to push the buttons right.

    I grab the Button ref like crtn does:

    AlertDialog dialog = bld.create();
    dialog.show(); //show() MUST be called before dialog.getButton
    Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
    

    But then I set the leftSpacer to View.GONE and the parent's gravity to CENTER_HORIZONTAL

    LinearLayout parent = (LinearLayout) positiveButton.getParent();
    parent.setGravity(Gravity.CENTER_HORIZONTAL);
    View leftSpacer = parent.getChildAt(1);
    leftSpacer.setVisibility(View.GONE);
    

    This has the advantage that it doesn't break the dialog's button stacking behavior. The disadvantage is that if the internal layout changes, it will break, so YMMV.

提交回复
热议问题