我可以创建和显示一个自定义警报对话框很好,但即使这样,我有android:layout_width/height=“fill_parent”在对话xml中,它只和内容一样大。
我想要的是填充整个屏幕的对话框,除了20像素的填充。 然后,作为对话框一部分的图像将自动使用fill_parent拉伸到完整的对话框大小。
我可以创建和显示一个自定义警报对话框很好,但即使这样,我有android:layout_width/height=“fill_parent”在对话xml中,它只和内容一样大。
我想要的是填充整个屏幕的对话框,除了20像素的填充。 然后,作为对话框一部分的图像将自动使用fill_parent拉伸到完整的对话框大小。
当前回答
...
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Dialog d = builder.create(); //create Dialog
d.show(); //first show
DisplayMetrics metrics = new DisplayMetrics(); //get metrics of screen
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = (int) (metrics.heightPixels*0.9); //set height to 90% of total
int width = (int) (metrics.widthPixels*0.9); //set width to 90% of total
d.getWindow().setLayout(width, height); //set layout
其他回答
***In Kotlin You can Code like This : -***
fun customDialog(activity: Activity?, layout: Int): Dialog {
val dialog = Dialog(activity!!)
try {
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCancelable(false)
dialog.setContentView(layout)
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.window!!.setLayout(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
dialog.show()
} catch (e: Exception) {
}
return dialog
}
实际90%计算解:
@Override public void onStart() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.getWindow()
.setLayout((int) (getScreenWidth(getActivity()) * .9), ViewGroup.LayoutParams.MATCH_PARENT);
}
}
其中getScreenWidth(Activity Activity)定义如下(最好放在Utils类中):
public static int getScreenWidth(Activity activity) {
Point size = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(size);
return size.x;
}
尝试将你的自定义对话框布局包装成RelativeLayout而不是LinearLayout。这对我很管用。
你必须在显示之前设置对话框的高度和宽度(dialog.show())
所以,像这样做:
dialog.getWindow().setLayout(width, height);
//then
dialog.show()
得到这段代码,我做了一些改变:
dialog.getWindow().setLayout((int)(MapGeaGtaxiActivity.this.getWindow().peekDecorView().getWidth()*0.9),(int) (MapGeaGtaxiActivity.this.getWindow().peekDecorView().getHeight()*0.9));
但是,当设备改变位置时,对话框的大小也会改变。当度量发生变化时,您可能需要自己处理。 peekDecorView,暗示在活动中的布局是正确初始化的,否则你可以使用
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int wwidth = metrics.widthPixels;
为了得到屏幕大小
试试这个:
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);