Android about dialog display location settings

The default display position of the custom dialog is the position of the window.
We can set the upper and lower positions of the dialog through the dialog or the window object window and then through the window.
For example, dialog.getWindow(); get the window object
window.setGravity(Gravity.CENTER); in the middle Position
window.setGravity(Gravity.BOTTEM); Bottom position
window.setGravity(Gravity.TOP); Top position
, etc. You can set it up, down, left and right

Now we set the dialog's position in the wendow, but this does not meet our needs. I want the dialog to be displayed at a distance from the top, such as 100 from the top. What should I do?

There is still a way to set
WindowManager.LayoutParams params = window.getAttributes(); Get the params of the window and then set the xy parameters to the params. The xy we set is the offset of the relative value relative to its own position. The negative value is invalid ( Obviously x is the offset representing the horizontal direction and y representing the offset in the vertical direction)
simply give a chestnut

   * 当参数值包含Gravity.LEFT时,对话框出现在左边,所以params.x就表示相对左边的偏移
     * 当参数值包含Gravity.RIGHT时,对话框出现在右边,所以params.x就表示相对右边的偏移
     * 当参数值包含Gravity.TOP时,对话框出现在上边,所以params.y就表示相对上边的偏移
     * 当参数值包含Gravity.BOTTOM时,对话框出现在下边,所以params.y就表示相对下边的偏移
注意 负值无效

Or the requirement I have just now, I have a dialog and want it to be displayed at a position 100 from the top

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = LayoutInflater.from(getActivity()).inflate(R.layout.home_identity_choose_window,
null);
builder.setView(view);
titleDialog = builder.create();
Window window = titleDialog.getWindow();
WindowManager.LayoutParams params = window.getAttributes();
params.x = 10;
params.y = 100;
params.width = 220;
params.height = 200;
window.setAttributes(params);
titleDialog.show();
window.setGravity(Gravity.TOP);

This will do

Another way is to set according to the screen ratio
// WindowManager m = getWindowManager();
// Display d = m.getDefaultDisplay(); // Get screen width and height
// WindowManager.LayoutParams params = dialogWindow.getAttributes();
/ / params.height = (int) (d.getHeight() * 0.5); // height is set to 0.5 of the screen
// params.width = (int) (d.getWidth() * 0.6); // width is set to 0.6 of the screen
// dialogWindow.setAttributes(params);
so you can freely set the position of the dialog

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325539745&siteId=291194637