我可以创建和显示一个自定义警报对话框很好,但即使这样,我有android:layout_width/height=“fill_parent”在对话xml中,它只和内容一样大。
我想要的是填充整个屏幕的对话框,除了20像素的填充。 然后,作为对话框一部分的图像将自动使用fill_parent拉伸到完整的对话框大小。
我可以创建和显示一个自定义警报对话框很好,但即使这样,我有android:layout_width/height=“fill_parent”在对话xml中,它只和内容一样大。
我想要的是填充整个屏幕的对话框,除了20像素的填充。 然后,作为对话框一部分的图像将自动使用fill_parent拉伸到完整的对话框大小。
当前回答
尝试将你的自定义对话框布局包装成RelativeLayout而不是LinearLayout。这对我很管用。
其他回答
我的答案是基于koma的,但它不需要覆盖onStart,但只需要onCreateView,当你创建新的片段时,默认情况下几乎总是被覆盖。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_fragment_layout, container);
Rect displayRectangle = new Rect();
Window window = getDialog().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
v.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
v.setMinimumHeight((int)(displayRectangle.height() * 0.9f));
return v;
}
我在Android 5.0.1上进行了测试。
下面的方法对我来说效果不错:
<style name="MyAlertDialogTheme" parent="Base.Theme.AppCompat.Light.Dialog.Alert">
<item name="windowFixedWidthMajor">90%</item>
<item name="windowFixedWidthMinor">90%</item>
</style>
(注:windowMinWidthMajor/Minor,如之前的答案所建议的,没有做到这一点。我的对话框不断改变大小取决于内容)
然后:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogTheme);
更简单的是这样做:
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.90);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.90);
alertDialog.getWindow().setLayout(width, height);
下面是我的自定义对话框宽度的变体:
DisplayMetrics displaymetrics = new DisplayMetrics();
mActivity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) (displaymetrics.widthPixels * (ThemeHelper.isPortrait(mContext) ? 0.95 : 0.65));
WindowManager.LayoutParams params = getWindow().getAttributes();
params.width = width;
getWindow().setAttributes(params);
因此,根据设备方向(ThemeHelper.isPortrait(mContext))对话框的宽度将是95%(纵向模式)或65%(横向模式)。这比作者要求的要多一点,但对某些人来说可能有用。
你需要创建一个从Dialog扩展而来的类,并把这段代码放到你的onCreate(Bundle savedInstanceState)方法中。
对于对话框的高度,代码应该类似于此。
尝试将你的自定义对话框布局包装成RelativeLayout而不是LinearLayout。这对我很管用。