create Dialog With Margin - Android android.app

Android examples for android.app:AlertDialog

Description

create Dialog With Margin

Demo Code

import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;

public class Main {

  public static AlertDialog createDialogWithMargin(Context context, int layout, boolean showSoftInput, int margin) {
    AlertDialog dialog = new AlertDialog.Builder(context).create();
    dialog.show();// w w  w .  java2 s .  c  o m
    dialog.setContentView(layout);
    Window window = dialog.getWindow();
    if (showSoftInput) {
      window
          .clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
      window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    Point size = displaySize(context);
    WindowManager.LayoutParams lp = window.getAttributes();
    lp.width = size.x - dpToPx(margin);
    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
    window.setAttributes(lp);

    return dialog;
  }

  public static Point displaySize(Context context) {
    WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = manager.getDefaultDisplay();
    Point point = new Point();
    display.getSize(point);
    return point;
  }

  public static int dpToPx(int dp) {
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
  }

}

Related Tutorials