如果你使用 AlertDialog 时,发现按钮的位置不符合你的预期,可以使用以下两种方式来调整按钮的位置。
示例代码:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("提示");
builder.setMessage("确定要执行该操作吗?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// 执行确定操作
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// 执行取消操作
}
});
AlertDialog dialog = builder.create();
dialog.show();
// 将确定按钮放在左边
Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setTextColor(Color.RED);
LinearLayout.LayoutParams positiveButtonLL = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
positiveButtonLL.gravity = Gravity.LEFT;
positiveButton.setLayoutParams(positiveButtonLL);
// 将取消按钮放在右边
Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
negativeButton.setTextColor(Color.BLUE);
LinearLayout.LayoutParams negativeButtonLL = (LinearLayout.LayoutParams) negativeButton.getLayoutParams();
negativeButtonLL.gravity = Gravity.RIGHT;
negativeButton.setLayoutParams(negativeButtonLL);
示例代码:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = LayoutInflater.from(context).inflate(R.layout.custom_alert_dialog_layout, null);
builder.setView(view);
AlertDialog dialog = builder.create();
dialog.show();
custom_alert_dialog_layout.xml 布局文件: