我想创建一个左对齐的alert dialog,但好像我们不能访问positive button的详细信息。这个答案是让按钮居中,但我想要它靠左对齐。我刚在stack上查了一下,并没有找到任何相关的内容。我不想为dialog创建custom_layout.xml。
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);
希望能对你有所帮助!
更多信息:现在我理解了问题,很遗憾你不能改变按钮的顺序。按钮的顺序为负面-中性-正面。但是一旦你拥有了按钮,你可以自由选择使用它们。例如,你可以通过在一行代码中将负面按钮重命名为正面按钮来使用负面按钮作为正面按钮。
new AlertDialog.Builder(activity)
.setNeutralButton("Your text", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//do what you want
}
}).show();
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);
如果你想要从右到左的标题,请设置:alertDialog.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);