Roger
Roger

Reputation: 6527

How to set dialog's position?

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>

Upvotes: 8

Views: 13779

Answers (5)

user1272377
user1272377

Reputation:

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.

Upvotes: 2

herbertD
herbertD

Reputation: 10985

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

Upvotes: 0

Felix
Felix

Reputation: 89626

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

Upvotes: 4

Michael
Michael

Reputation: 688

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

Upvotes: 2

Felix
Felix

Reputation: 89626

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.

Upvotes: 8

Related Questions