在 Andrey T (https://stackoverflow.com/a/29662638/1317564) 的链接答案的帮助下,这是我想出的解决方法:
首先,您创建一个实用方法,该方法仅在需要包装按钮时才包装按钮:
public static void applyWorkaroundForButtonWidthsTooWide(Button dialogButton) {
if (dialogButton == null)
return;
if (!(dialogButton.getParent() instanceof LinearLayout))
return;
// Workaround for buttons too large in alternate languages.
final LinearLayout linearLayout = (LinearLayout) dialogButton.getParent();
linearLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
int oldRight, int oldBottom) {
if (right - left > 0) {
final int parentWidth = linearLayout.getWidth();
int childrenWidth = 0;
for (int i = 0; i < linearLayout.getChildCount(); ++i)
childrenWidth += linearLayout.getChildAt(i).getWidth();
if (childrenWidth > parentWidth) {
// Apply stacked buttons
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(linearLayout.getPaddingLeft(), 0, linearLayout.getPaddingRight(),
linearLayout.getPaddingBottom());
for (int i = 0; i < linearLayout.getChildCount(); ++i) {
if (linearLayout.getChildAt(i) instanceof Button) {
final Button child = (Button) linearLayout.getChildAt(i);
child.setGravity(Gravity.END | Gravity.CENTER_VERTICAL);
final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) child.getLayoutParams();
params.width = LinearLayout.LayoutParams.MATCH_PARENT;
params.gravity = Gravity.END;
child.setLayoutParams(params);
} else if (linearLayout.getChildAt(i) instanceof Space) {
linearLayout.removeViewAt(i--);
}
}
}
linearLayout.removeOnLayoutChangeListener(this);
}
}
});
}
您可以添加额外的错误处理(即尝试/捕获)并根据需要进一步自定义。
现在,当显示对话框时调用此实用方法:
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
MaterialAlertDialogUtils.applyWorkaroundForButtonWidthsTooWide(dialog.getButton(AlertDialog.BUTTON_POSITIVE));
}
});
这可以解决问题,并且只会在需要时包装按钮。我一直在使用它,因为即使是两个按钮的对话框也可能需要用德语包装,而三按钮的对话框肯定需要它在许多语言中。