Home » Android » java – How to set dialog's position?

java – How to set dialog's position?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have made a custom dialog.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="myBackgroundStyle"
        parent="@android:style/Theme.Translucent.NoTitleBar" />
</resources>

screenshot

Dialog dialog = new Dialog(this, R.style.myBackgroundStyle);
dialog.setContentView(R.layout.dialog);

dialog.show();

WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.y = 225; params.x = 225;
params.gravity = Gravity.TOP | Gravity.LEFT;       
dialog.getWindow().setAttributes(params); 

But the problem is that it appears in the top left corner and I can’t find a way to place it where I need it. params.y=225; params.x=225; somehow don’t affect it.

Any ideas?


edit:
If I have the xml like that ( style/Theme.Dialog ), then the parameters and location work fine, but a modal shadow appears. Is there a way to remove it?

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="myBackgroundStyle" parent="@android:style/Theme.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">false</item>
    </style>
</resources>
How to&Answers:

Try using Theme.Panel as the style’s parent instead.

Answer:

Try creating a new set of parameters:

WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.y = 225; params.x = 225;
params.gravity = Gravity.TOP | Gravity.LEFT;       
dialog.getWindow().setAttributes(params);

Edit: if you want to preserve the window’s attributes, you could try adding this as the second line:

params.copyFrom(dialog.getWindow().getAttributes());

However, note that the copyFrom method is completely undocumented, so I have no idea if it does what it sounds like it does.

Answer:

not 100% sure, but is it something to do with params.gravity=Gravity.TOP | Gravity.LEFT;?

another edit

ok then, this one should be of more use: Calling android dialog without it fading the background

Answer:

In the above code the line…

dialog.show();

Should appear after

WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.y = 225; params.x = 225;
params.gravity = Gravity.TOP | Gravity.LEFT;       
dialog.getWindow().setAttributes(params); 
...

By the looks of things you are showing the dialog first then setting x,y coordinates after the dialog has already been drawn to the screen.

Answer:

Just remove params.gravity = Gravity.TOP | Gravity.LEFT; and it will works. I’ve tried.