Changing position of the Dialog on screen android
Asked Answered
M

18

136

I made a simple AlertDialog in my Activity:

View view = layoutInflater.inflate(R.layout.my_dialog, null);
AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
                    .setView(view)  
                    .create();

infoDialog.show();

With above code, the dialog shows at the (about) the center of the screen.

I am wondering, how can I customize the dialog position to make it showing just under the top Action Bar ? (Is there anyway to change the gravity or something of the dialog?) and how to do it based on my code??

Madelon answered 27/2, 2012 at 14:52 Comment(3)
If you show us your my_dialog xml layout we can probably help you make changes.Ladle
duplicate?#5469505Porch
@ Ankit, can you put your comment as an answer, because my problem get solved after checking your link.Madelon
R
290

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about

Recommendation answered 27/2, 2012 at 14:59 Comment(8)
Hi, thank you. I set its gravity to top, the dialog goes on the top of the screen, but it also covered my action bar, I would like the dialog on top but just under the action bar...how to adjust this?Madelon
You might try using wlp.x and wlp.y fields to explicitly set the location of the dialog on screen. I haven't tried it myself, but it should probably work.Recommendation
The clearing of the dimming didn't work for me (though the rest worked like a charm). I found a solution to the dimming in another spot, in the form of: window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);Zaxis
@AleksG is there a way to also change color of dim background keeping dailog at center? I tried setting windowIsFloating=false to dailog style. But it align dailog to top!Nammu
@Nammu If you want to keep dialogue in the centre, you don't need any of this code - Android centres dialogues by default. As for changing the dim colour, this is controlled by the theme. You may be able to override it by including corresponding theme in your app. I never tried it though.Recommendation
By WindowManager source, wlp.y only works if the gravity is setted to TOP or BOTTOMRonel
Remove wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND; to get back your shadows.Suiter
@KyleR If you look at the date of the answer, you'll realise that it was written way before API 22 (I believe, I was using API 11 at the time). When you have floating buttons (i.e. full screen app), all app UI will be behind the floating navigation buttons - always.Recommendation
T
28
private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Trakas answered 27/2, 2012 at 14:57 Comment(4)
Hi, thank you. I set its gravity to top, the dialog goes on the top of the screen, but it also covered my action bar, I would like the dialog on top but just under the action bar...how to adjust this?Madelon
you can set margin top of layoutTrakas
'FILL_PARENT' is deprecated. I am on API 21. As by Developer ReferenceConstance
@Constance so use 'MATCH_PARENT' insteadAftercare
P
28

I found this code snippet from @gypsicoder code here

    private CharSequence[] items = {"Set as Ringtone", "Set as Alarm"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

            if(item == 0) {

            } else if(item == 1) {

            } else if(item == 2) {

            }
        }
    });
    
    AlertDialog dialog = builder.create();
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();
    
    wmlp.gravity = Gravity.TOP | Gravity.LEFT;
    wmlp.x = 100;   //x position
    wmlp.y = 100;   //y position
    
    dialog.show();

Here x position's value is pixels from left to right. For y position value is from bottom to top.

Pelvic answered 11/6, 2016 at 23:0 Comment(2)
You forgot to set the LayoutParams after modifying them.Muscovite
@HarshVardhan the parameters are modified within the object returned by getAttributes(), which is the actual object used by the window manager.Exoteric
G
16

For me, this worked out pretty well where I was trying to position my dialog somewhere exactly at the bottom of the textview where it gets selected.

public void setPosition(int yValue) {
    Window window = getWindow();
    WindowManager.LayoutParams param = window.getAttributes();
    param.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
    param.y = yValue;
    window.setAttributes(param);
    window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
Gastric answered 30/6, 2015 at 10:57 Comment(1)
Yes it is working with the Y position, but when I set the X position then it has no effect on the X positionLutz
U
15

New BottomSheetDialog:

BottomSheetDialog dialog = new BottomSheetDialog(YourActivity.this);    
dialog.setContentView(YourView);

dialog.show();
Unhopedfor answered 2/8, 2017 at 14:21 Comment(0)
U
9

just add this to your code:

dialog.getWindow().setGravity(Gravity.BOTTOM);
Unconformity answered 16/10, 2017 at 7:0 Comment(0)
M
4

in Java

AlertDialog.Builder builder = new AlertDialog.Builder(ConnectActivity.this);

AlertDialog alertDialog = builder.create();  
// set the gravity      
alertDialog.getWindow().setGravity(Gravity.TOP);
// set the margin 
alertDialog.getWindow().getAttributes().verticalMargin = 0.1F;
alertDialog.show();
Mole answered 4/11, 2021 at 12:37 Comment(0)
B
3

use bottomSHeet :

BottomSheetDialog dialog = new BottomSheetDialog(YourActivity.this);
dialog.setContentView(YourView);
dialog.show();
Batavia answered 15/12, 2019 at 7:0 Comment(0)
S
3

You can use this snippet to place the AlertDialog at the bottom of the screen.

AlertDialog dialogPopup;

dialogPopup = mBuilder.create();
dialogPopup.getWindow().getAttributes().gravity = Gravity.BOTTOM;
Saied answered 2/10, 2020 at 18:18 Comment(0)
S
3

kotlin:

val dialog = Dialog(context)
//set graviy bottom
dialog.window.setGravity(Gravity.BOTTOM)
Squall answered 19/8, 2021 at 0:58 Comment(0)
W
3

The easiest way to set Dialog gravity in kotlin:

dialog.window?.setGravity(Gravity.TOP) // Set the gravity here
private fun searchDialog() {
    val dialog = Dialog(this)
    dialog.window?.setGravity(Gravity.TOP) // Set the gravity here
    val binding = DialogSearchHomeBinding.inflate(layoutInflater)
    dialog.setContentView(binding.root)
    dialog.show()
}
Wanigan answered 4/2, 2022 at 4:33 Comment(0)
P
2
dialog.getWindow().getAttributes().gravity = Gravity.BOTTOM;
Psychognosis answered 4/7, 2017 at 6:31 Comment(0)
P
2
public class MyDialogFragment extends DialogFragment{
    protected void setDialogGravity(int gravity) {
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                WindowManager.LayoutParams params = window.getAttributes();
                params.width = WindowManager.LayoutParams.MATCH_PARENT;
                params.height = WindowManager.LayoutParams.MATCH_PARENT;
                params.horizontalMargin = 0;
                params.gravity = gravity;
                params.dimAmount = 0;
                params.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
                window.setAttributes(params);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);

        return inflater.inflate(R.layout.my_dialog, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
                super.onViewCreated(view, savedInstanceState);
                setDialogGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
    }
}
Pugging answered 23/11, 2018 at 6:38 Comment(0)
E
2

i use this method

 @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Dialog dialog = new Dialog(getActivity());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    Window window = dialog.getWindow();
    WindowManager.LayoutParams wlp = window.getAttributes();
    wlp.gravity = Gravity.BOTTOM;
    dialog.setContentView(R.layout.dialog_droppoint);
    dialog.show();
    window.setAttributes(wlp);
    return dialog;

}
Eschatology answered 7/8, 2019 at 16:30 Comment(0)
N
1

For my Dialog activity i used this one:

WindowManager.LayoutParams lp = this.getWindow().getAttributes();
lp.gravity = Gravity.BOTTOM;
Nurmi answered 13/5, 2019 at 14:14 Comment(0)
J
1

For showing dialog at a certain position just add this line at the onViewCreated method.

dialog?.window?.attributes?.gravity = Gravity.BOTTOM

for sure you can use any gravity value.

Josephson answered 30/11, 2022 at 22:1 Comment(0)
S
0

I have coded a custom Dialog, with a custom layout. It has a cancel and a save button and you can set up also gravity on the device's screen (bottom) and define the width and height of the dialog.

private void showDialog(final String scanContent, final String currentTime, final String currentDate) { LayoutInflater linf = LayoutInflater.from(this); final View inflator = linf.inflate(R.layout.dialog_barcode_result_dialog, null);

final Dialog dialog = new Dialog(this, android.R.style.Theme_DeviceDefault_Light_Dialog);

// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.BOTTOM);

dialog.getWindow().setLayout(375, 350);

window.setLayout(WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.dialog_barcode_result_dialog);

dialog.setTitle(getResources().getString(R.string.dialog_title));
dialog.setContentView(inflator);

final Button save = inflator.findViewById(R.id.saveBtn);
final Button cancel = inflator.findViewById(R.id.cancelBtn);
final TextView message = inflator.findViewById(R.id.dialog_message_text);
message.setText(scanContent);
save.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        dialog.cancel();

    }
});
cancel.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        dialog.cancel();

    }
});

dialog.show();

}

the dialog layout xml file is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:minWidth="350dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:textSize="16sp"
                android:layout_marginBottom="10dp"
                android:id="@+id/dialog_message_text"
                />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="right"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/cancelBtn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/cancel" />

                <Button
                    android:id="@+id/saveBtn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/button_save" />
            </LinearLayout>

        </LinearLayout>
    </ScrollView>
</LinearLayout>
Straticulate answered 28/6, 2021 at 12:18 Comment(0)
R
0

Java version of kotlin code suggested by A.I.Shakil :

 AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
            .setView(v)
            .setCancelable(false).create();
    dialog.getWindow().setGravity(Gravity.TOP);
    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    dialog.show();
Rubinstein answered 14/2, 2022 at 8:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.