I use this codes for Android (Java) programming:
public static MessageBoxResult showOk(
Context context, String title, String message, String okMessage)
{
okDialogResult = MessageBoxResult.Closed;
// make a handler that throws a runtime exception when a message is received
final Handler handler = new Handler()
{
@Override
public void handleMessage(Message mesg)
{
throw new RuntimeException();
}
};
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(title);
alert.setMessage(message);
alert.setPositiveButton(okMessage, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
okDialogResult = MessageBoxResult.Positive;
handler.sendMessage(handler.obtainMessage());
}
});
AlertDialog dialog = alert.show();
// align button to center
Button b = (Button) dialog.findViewById(android.R.id.button1);
b.setGravity(Gravity.CENTER_HORIZONTAL);
// loop till a runtime exception is triggered.
try { Looper.loop(); }
catch(RuntimeException e2) {}
return okDialogResult;
}
My problem is how make center the button? As you see I try to align button to cnenter using Gravity.CENTER_HORIZONTAL
(also .CENTER
) but nothing changes. The button is almost in right position.
Here is something really work.
The parent of the 3 buttons (neutral, positive ve and negative) is ButtonBarLayout, which extends LinearLayout. To centralize a view in LinearLayout, weight, width and layout_gravity(but not gravity) is important, and these code works perfectly:
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:
in onStart():
If you want to have Positive And Negative Buttons at the same time (Large & Center), you can use something like this:
I presume you are using the AlertDialog from the Support library.
If that's the case try replacing your import to android.app.AlertDialog.
This worked for me :
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 aLinearLayout
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:But then I set the leftSpacer to View.GONE and the parent's gravity to CENTER_HORIZONTAL
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.