Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get dialog size?

I am looking for a way to get size of a custom dialog. I went through this question, but the only answer given is pretty useless, because if I try mDialog.getWindow().getAttributes().height; it only returns -2, which is a constant for WRAP_CONTENT attribute which I set to dialog. How can I get the size of it. I want to know the siye for the background image.

like image 435
slezadav Avatar asked Nov 22 '12 15:11

slezadav


4 Answers

In case, if you have your own XML layouts for custom dialog.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/dialog_main_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:background="@color/primaryBackground">

    /* whatever you want here */

</android.support.constraint.ConstraintLayout>

In activity:

    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.popup_gameover);

    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface d) {
            View view = dialog.findViewById(R.id.dialog_main_layout);
            int width = view.getWidth();
            int height = view.getHeight();

            ...
        }
    });

This width and height exacly as expected.

like image 78
Alexey Ishkov Avatar answered Nov 01 '22 14:11

Alexey Ishkov


Give it a try:

mDialog.getWindow().getDecorView().getHeight() 
like image 23
Korniltsev Anatoly Avatar answered Nov 01 '22 14:11

Korniltsev Anatoly


Actually, in Android it doesn't work like in iOS - you can't get the size of the View itself, what you can do, though, is to ask for the size of the ROOT layout of that view.

e.g.:

myDialog.this.findViewById(R.id.dialog_root_layout).getHeight());

like image 23
Michal Avatar answered Nov 01 '22 12:11

Michal


@Kormilsev Anatoliy has answered correct and I am just improving. So in the class you inherit from Dialog class just override the method:

@Override
public void onWindowFocusChanged (boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    height = getWindow().getDecorView().getHeight();
}
like image 20
CodeToLife Avatar answered Nov 01 '22 14:11

CodeToLife