4

I want to create an alert dialog with ltr buttons. but it seems like we can't access positive button details.

this answer was for aligning buttons to center, but I want to align it to the left.

I just checked stack and didn't find anything that covers this.i don't want to create custom_layout.xml for dialog.

Gaurav Mall
  • 2,372
  • 1
  • 17
  • 33

2 Answers2

2

This is the answer from the link you posted. You need to change the weight of the layout params from 10 to -10 to go from center to left.

 AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
 alertDialog.setTitle("Title");
 alertDialog.setMessage("Message");

 alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes",
             new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

alertDialog.show();

Button btnPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
Button btnNegative = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);

LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) btnPositive.getLayoutParams();

//Changing the weight to negative pushes it to the left.
layoutParams.weight = -10;

btnPositive.setLayoutParams(layoutParams);
btnNegative.setLayoutParams(layoutParams);

Hope it helps!

More information: Now that I understand the question, no sadly you cannot change the order or the buttons. The order is NEGATIVE - NEUTRAL - POSITIVE. But once you have the button you can choose whatever to do with. For instance, you can use the negative button as the positive, by just renaming it in one line.

Gaurav Mall
  • 2,372
  • 1
  • 17
  • 33
  • 1
    Why doesn't it, I tried it and it worked fine. Did you try something else? – Gaurav Mall Jul 02 '19 at 07:58
  • we just push the buttons to the left, but still, the positive button is right of the negative button.how should I change their positions? @gaurav-mall – Mehran Mahmoudkhani Jul 02 '19 at 08:16
  • 1
    You should add a neutral button too then. – Gaurav Mall Jul 02 '19 at 08:17
  • @VikaS Haven't tried it out yet, but if it is not, then look for newer posts. This was a solution to a very specific problem, so it would be better if you saw the generic solution on a newer post. I don't think this answer deserves an edit. – Gaurav Mall Jan 29 '20 at 20:04
2

You can try this ;

new AlertDialog.Builder(activity)
            .setNeutralButton("Your text", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //do what you want
                }
            }).show();
JDevoloper
  • 227
  • 4
  • 17