这是AlertDialog 的默认行为。要将按钮与底部对齐,您还必须将警报容器 AlertDialogLayout 的高度更改为 MATCH_PARENT。不幸的是,目前没有公共 API 可以从 AlertDialog 检索 AlertDialogLayout,所以下面我将描述两种可能的解决方案来从 AlertDialog 检索它并更改其高度。
1.直接从PositiveButton中找到AlertDialogLayout:
Button btn = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
AlertDialogLayout alertDialogLayout = (AlertDialogLayout) btn.getParent().getParent().getParent();
alertDialogLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
2.从PositiveButton根视图开始循环查找AlertDialogLayout:
Button btn = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
View rootView = btn.getRootView();
findAlertDialogLayoutAndSetParams(rootView);
findAlertDialogLayoutAndSetParams(View view) 是一个辅助函数,它会重复出现,直到找到 AlertDialogLayout:
private void findAlertDialogLayoutAndSetParams(View view){
if(view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup)view;
for(int i = 0; i < viewGroup.getChildCount(); i++) {
View childView = viewGroup.getChildAt(i);
if(childView instanceof ViewGroup) {
if(childView instanceof AlertDialogLayout){
AlertDialogLayout alertDialogLayout = (AlertDialogLayout)childView;
alertDialogLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
}
else {
findAlertDialogLayoutAndSetParams(childView);
}
}
}
}
}
完整示例:
//get your custom view
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View wifiResultView = mInflater.inflate(R.layout.alert_view_layout, null, false);
//create the MaterialAlertDialogBuilder
MaterialAlertDialogBuilder alert = new MaterialAlertDialogBuilder(context);
alert.setPositiveButton("Ok", null);
alert.setNeutralButton("Cancel", null);
alert.setView(wifiResultView);
AlertDialog alertDialog = alert.show();
alertDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//stick the buttons to the bottom by setting the height of AlertDialogLayout to MATCH_PARENT
//1st option - get the AlertDialogLayout directly from the positive button
Button btn = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
AlertDialogLayout alertDialogLayout = (AlertDialogLayout) btn.getParent().getParent().getParent();
alertDialogLayout.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//2nd option - find AlertDialogLayout in a recurring way starting from the positive button root view
//Button btn = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
//View rootView = btn.getRootView();
//findAlertDialogLayoutAndSetParams(rootView);
之前/之后的结果: