Change buttons' order of DatePickerDialog for

2019-04-15 08:49发布

问题:

I created an DatePickerDialog :

DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);

and show it On Android 4.0.3 (API 15) device, it looks like this:

As you see above, the "cancel" button is displaying on the left-hand side while the "Set" button is on the right-hand side. But on Android 2.3.3, the button order is the other way around.

So, how can I change the buttons' order of DatePickerDialog in order to show "Set" button on left-hand side, and "cancel" button on right-hand side on Android 4.0.3 device?

回答1:

So, how can I change the buttons' order of DatePickerDialog in order to show "Set" button on left-hand side, and "cancel" button on right-hand side on Android 4.0.3 device?

You don't. Either you leave them alone, or you create your own dialog with your own DatePicker that has the buttons in the wrong order.

Please bear in mind that most users of Android apps use more than just your Android app. They actually use other apps. Some of those other apps will use a DatePickerDialog, and those dialogs will have the button order as shown in your screenshot. It is much more important for your users for you to stick to the device standard (so all their DatePickerDialogs work the same) than it is for you to force the wrong button order on some devices.



回答2:

Actually you can and you don't need to create your own custom dialog:

... 
datePickerDialog.show();

    Button negativeButton = datePickerDialog.getButton(DatePickerDialog.BUTTON_NEGATIVE);
    ViewParent buttonParent = negativeButton.getParent();

    if (buttonParent instanceof LinearLayout)
    {
        LinearLayout datePickerDialogLayout = ((LinearLayout) buttonParent);
        datePickerDialogLayout.removeView(negativeButton);
        datePickerDialogLayout.addView(negativeButton);
    }

So what we do here is:

1) After showing the dialog(!), we remove a negative button ('Cancel' in your case) from its parrent layout. When it is removed, the 'Set' button (or any other button which is in the dialog) becomes the last element in the layout.

2) Add it (negative button) again. So, the last added view becomes the last element in the parent layout, i.e. dialog.