如何将警示对话框按钮左对齐?

5
我想创建一个左对齐的alert dialog,但好像我们不能访问positive button的详细信息。这个答案是让按钮居中,但我想要它靠左对齐。我刚在stack上查了一下,并没有找到任何相关的内容。我不想为dialog创建custom_layout.xml。
3个回答

2
这是您发布的链接中的答案。要从中心到左侧移动,请将布局参数的权重从10更改为-10。
 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);

希望能对你有所帮助!

更多信息:现在我理解了问题,很遗憾你不能改变按钮的顺序。按钮的顺序为负面-中性-正面。但是一旦你拥有了按钮,你可以自由选择使用它们。例如,你可以通过在一行代码中将负面按钮重命名为正面按钮来使用负面按钮作为正面按钮。


1
为什么它不行?我试过了,而且还完全没问题。你试过其他的方法吗? - Gaurav Mall
我们只是把按钮向左推,但是正按钮仍然在负按钮的右边。我该如何改变它们的位置? @gaurav-mall - Mehran Mahmoudkhani
1
你应该也加上一个中立的按钮。 - Gaurav Mall
@VikaS 我还没有尝试过,但如果不是,请查找更新的帖子。这是一个非常特定问题的解决方案,所以最好在更新的帖子上看到通用解决方案。我认为这个答案不需要编辑。 - Gaurav Mall

2
你可以尝试这个;
new AlertDialog.Builder(activity)
            .setNeutralButton("Your text", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //do what you want
                }
            }).show();

0
尝试这个(主题:MaterialAlertDialog_Material3,并移除中性按钮和负面按钮之间的空格)
    AlertDialog alertDialog = new AlertDialog.Builder(activity, R.style.MaterialAlertDialog_Material3)
                .setNeutralButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //do what you want
                    }
                }).setNegativeButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //do what you want
                    }
                }).create();
    alertDialog.show();
    alertDialog.getWindow().findViewById(R.id.spacer).setVisibility(View.GONE);

enter image description here

如果你想要从右到左的标题,请设置:
alertDialog.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接