16

I have used Dialog for display ad in my Andorid app.But I have to display this Dialog about 50dp top from buttom so i think we should set Dialog Gravity buttom and set its buttom margine 50dp.But i'm unable to use margin in Dialog.so please can suggest me how to solve this.

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/popup_element"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dialogback"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Java:

final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
LayoutInflater inflator = (LayoutInflater) getApplicationContext()
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflator.inflate(R.layout.ad, null, false);
dialog.setContentView(view);
dialog.getWindow().setGravity(Gravity.BOTTOM);
dialog.setCancelable(true);
WebView webView = (WebView) dialog.findViewById(R.id.webView);
webView.loadUrl("");
webView.setWebViewClient(new MyWebViewClient());
webView.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        dialog.dismiss();
    }
});
dialog.show();
Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
Dilip
  • 2,271
  • 5
  • 32
  • 52
  • The answer on this link save huge amount of my time. https://stackoverflow.com/questions/26336302/how-to-set-dialog-outer-margins-android/49010511#49010511?newreg=7fe3448044b5406ca2a2dc8866159e72 – Sardorbek Kurbonov Mar 10 '21 at 07:19

7 Answers7

27

I did a similar smiley dialog. I extend dialog

public class SmileCustomDialog extends Dialog {
Context mcontext;
GridView mGridview;

public GridView getGridview() {
    return mGridview;
}

public SmileCustomDialog(final Context context) {
    super(context, R.style.SlideFromBottomDialog);
    this.mcontext = context;
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.emocategorydialog, null);
    mGridview = (GridView) v.findViewById(R.id.emogrid);
    mGridview.setSelector(new ColorDrawable(Color.TRANSPARENT));

    ImageAdapter mAdapter = new ImageAdapter(mcontext);
    mGridview.setAdapter(mAdapter);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.setContentView(v);

    WindowManager.LayoutParams params = this.getWindow().getAttributes();
    this.setCanceledOnTouchOutside(true);
    params.y = -100;
    this.getWindow().setAttributes(params);

}

}

But the essential is

WindowManager.LayoutParams params = yourDialog.getWindow().getAttributes(); // change this to your dialog.

params.y = -100; // Here is the param to set your dialog position. Same with params.x
        yourDialog.getWindow().setAttributes(params);

Just add this before your show your dialog.

anand
  • 416
  • 2
  • 11
Trung Nguyen
  • 7,442
  • 2
  • 45
  • 87
  • 1
    what if i want to set padiding from left and right. i tried to do that with param.x with Gravity but that didn;t work. – Vaishali Sharma Apr 29 '15 at 06:03
  • I did not use your entire solution, but `this.setCanceledOnTouchOutside(true);` was KEY to fixing a problem I had using another solution! – Carl Smith Mar 31 '21 at 09:44
24

WindowManager.LayoutParams:
public int x: X position... When using LEFT or START or RIGHT or END it provides an offset from the given edge
public int y: Y position... When using TOP or BOTTOM it provides an offset from the given edge
(http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#x)
thus:

final Dialog dialog = new Dialog(context);
    // ...
    // e.g. top + right margins:
    dialog.getWindow().setGravity(Gravity.TOP|Gravity.RIGHT);
    WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
    layoutParams.x = 100; // right margin
    layoutParams.y = 170; // top margin
    dialog.getWindow().setAttributes(layoutParams);
    // e.g. bottom + left margins:
    dialog.getWindow().setGravity(Gravity.BOTTOM|Gravity.LEFT);
    WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
    layoutParams.x = 100; // left margin
    layoutParams.y = 170; // bottom margin
    dialog.getWindow().setAttributes(layoutParams);

// etc.
Sergey Burish
  • 584
  • 6
  • 8
6

You can create a style for your dialog and put margins there.

For example:

<style name="custom_style_dialog"> 
    <item name="android:layout_marginStart">16dp</item>
    <item name="android:layout_marginEnd">16dp</item>
</style>

Then, in your dialog class:

class CountryDialog(
    context: Context
) : Dialog(context, R.style.custom_style_dialog) {

  //your code here
}
foxtrotuniform6969
  • 3,527
  • 7
  • 28
  • 54
4

This is an approach to set all four margins without having to care about gravity.

I tested my approach for a DialogFragment by applying it in the onCreateDialog method:

public Dialog onCreateDialog( Bundle savedInstanceState )
{
    // create dialog in an arbitrary way
    Dialog dialog = super.onCreateDialog( savedInstanceState ); 
    DialogUtils.setMargins( dialog, 0, 150, 50, 75 );
    return dialog;
}

This is the method applying the margins to the dialog:

public static Dialog setMargins( Dialog dialog, int marginLeft, int marginTop, int marginRight, int marginBottom )
{
    Window window = dialog.getWindow();
    if ( window == null )
    {
        // dialog window is not available, cannot apply margins
        return dialog;
    }
    Context context = dialog.getContext();

    // set dialog to fullscreen
    RelativeLayout root = new RelativeLayout( context );
    root.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) );
    dialog.requestWindowFeature( Window.FEATURE_NO_TITLE );
    dialog.setContentView( root );
    // set background to get rid of additional margins
    window.setBackgroundDrawable( new ColorDrawable( Color.WHITE ) );

    // apply left and top margin directly
    window.setGravity( Gravity.LEFT | Gravity.TOP );
    LayoutParams attributes = window.getAttributes();
    attributes.x = marginLeft;
    attributes.y = marginTop;
    window.setAttributes( attributes );

    // set right and bottom margin implicitly by calculating width and height of dialog
    Point displaySize = getDisplayDimensions( context );
    int width = displaySize.x - marginLeft - marginRight;
    int height = displaySize.y - marginTop - marginBottom;
    window.setLayout( width, height );

    return dialog;
}

Here are the helper methods I used:

@NonNull
public static Point getDisplayDimensions( Context context )
{
    WindowManager wm = ( WindowManager ) context.getSystemService( Context.WINDOW_SERVICE );
    Display display = wm.getDefaultDisplay();

    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics( metrics );
    int screenWidth = metrics.widthPixels;
    int screenHeight = metrics.heightPixels;

    // find out if status bar has already been subtracted from screenHeight
    display.getRealMetrics( metrics );
    int physicalHeight = metrics.heightPixels;
    int statusBarHeight = getStatusBarHeight( context );
    int navigationBarHeight = getNavigationBarHeight( context );
    int heightDelta = physicalHeight - screenHeight;
    if ( heightDelta == 0 || heightDelta == navigationBarHeight )
    {
        screenHeight -= statusBarHeight;
    }

    return new Point( screenWidth, screenHeight );
}

public static int getStatusBarHeight( Context context )
{
    Resources resources = context.getResources();
    int resourceId = resources.getIdentifier( "status_bar_height", "dimen", "android" );
    return ( resourceId > 0 ) ? resources.getDimensionPixelSize( resourceId ) : 0;
}

public static int getNavigationBarHeight( Context context )
{
    Resources resources = context.getResources();
    int resourceId = resources.getIdentifier( "navigation_bar_height", "dimen", "android" );
    return ( resourceId > 0 ) ? resources.getDimensionPixelSize( resourceId ) : 0;
}

The helper methods are explained in another of my SO answers.

This Gist contains an extended versions that supports immersve mode too.

Community
  • 1
  • 1
Peter F
  • 3,633
  • 3
  • 33
  • 45
3
View view = layoutInflater.inflate(R.layout.dialog_layout, null);
        AlertDialog infoDialog = new AlertDialog.Builder(this)
        .setView(view)  
        .create();
        Window window =infoDialog.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND );
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.dimAmount=(float) 0.0;
        //wlp.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND ;

        window.setAttributes(wlp);
        infoDialog.show();

Change gravity to bottom

Jaiprakash Soni
  • 4,100
  • 5
  • 36
  • 67
1

Well, what best worked for me was to wrap my dialog view inside a FrameLayout and add padding, and set onClickListener to "dismiss" dialog. Like this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/parentFl"
    android:background="@android:color/transparent"
    android:padding="@dimen/vvlarge_margin">


 dialog?.window?.setBackgroundDrawable(context?.getDrawable(android.R.color.transparent))
 view.parentFl.setOnClickListener { dismiss() }
M. Usman Khan
  • 3,689
  • 1
  • 59
  • 69
0

Another approach is to use the InsetDrawable. You simply specify the insetLeft & insetRight and apply it as your background like below:

inset_drawable.xml (Created in the drawable folder)

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/dialog_bg" <!-- this is simply a shape drawable with corners applied-->
android:insetLeft="30dp" <!-- specify your dimension -->
android:insetRight="30dp" />

your_layout.xml (Your custom dialog)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/popup_element"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/inset_drawable"
android:orientation="vertical" >

<WebView
    android:id="@+id/webView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>
Oush
  • 3,090
  • 23
  • 22