I have created a Custom AlertDialog like this -
remark_builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the
// dialog layout
remark_builder.setCancelable(true);
final View dialogView = inflater.inflate(R.layout.add_remark_dialog, null);
remark_builder.setView(dialogView);
if (remark_dialog == null || !remark_dialog.isShowing()) {
remark_dialog = remark_builder.create();
remark_dialog.setCanceledOnTouchOutside(false);
remark_dialog.show();
}
I want to add margins to the left and right of this alertdialog.
I have tried a lot of code over the internet but it is emphasizing on setting the width and height of the Alert Dialog.
I don't want to set the width and height. I want to add margins to the left and right of the AlertDialog which is MATCH_PARENT.
My current alert dialog looks like :
I want to add margins like 40 or 50 or according to the device density. is this possible?
You can try the below method to achieve this.
Rect displayRectangle = new Rect();
Window window = mContext.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
remark_dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
malertdialog.show();
malertdialog.getWindow().setLayout((int)(displayRectangle.width() *
0.8f), (int)(displayRectangle.height() / 2));
adjust the decimal value for the width and height as per what ratio you need.
Related
I have a relative layout that occupies 100% of the screen. I call many custom dialogs and always works well. I get positioning and correct height and width with no problems.
However, now I need a dialog that is 100% of screen height and 100% of screen width. I get 100% width but I don't get 100% height. The maximum is around 95 of height.
I've reduced my code to a minimum for better clarity:
var lay = RelativeLayout(this)
var dial = Dialog(cx)
val win = dial.window
val wlp = win.attributes
win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
wlp.apply {
gravity = Gravity.TOP or Gravity.LEFT
x = 0
y = 0
}
win.attributes = wlp
// Here are my widgets linked to lay with lay.addView(widget).
dial.setContentView( // Connection between layout and dialog
lay, ViewGroup.LayoutParams(
screen_width, // variable with screen width in pixels
screen_height )) // variable with screen heigth in pixels
I've read many questions in Stackoverflow. What I have tried:
a) I've used MATCH_PARENT as height.
b) I've tried some windows flags:
win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
win.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
c) I've tried windows attribute property:
wlp.verticalMargin = 0F
No success.
PS: I also have a strange shade border at right and bottom side of dialog that I cannot get rid of it.
Update:
Rahul Khurana solution has killed the problem.
It just use
val dial = Dialog(cx,android.R.style.Theme_Black_NoTitleBar_Fullscreen)
It also eliminates the shade in other no fullscreen dialogs
val dial = Dialog(cx,
android.R.style.Theme_DeviceDefault_Dialog_NoActionBar)
Change the constructor like this:
val dialog=Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
Initialize and show your dialog as below in onStart
override fun onStart() {
super.onStart()
val dial = Dialog(this);
var width = ViewGroup.LayoutParams.MATCH_PARENT;
var height = ViewGroup.LayoutParams.MATCH_PARENT;
dial.getWindow().setLayout(width, height);
dial.show()
}
Use this snippet of code, it will work.
Activity activity = ...;
AlertDialog dialog = ...;
// retrieve display dimension
Rect displayRectangle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
// inflate layout
LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.your_layout, null);
layout.setMinimumWidth((int)(displayRectangle.width() * 0.95f));
layout.setMinimumHeight((int)(displayRectangle.height() * 0.95f));
dialog.setView(layout);
dialog?.window?.apply {
requestFeature(Window.FEATURE_NO_TITLE); setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT)
}
I have studied many questions and answers in Stackoverflow, then I made a dummy function, that I run after a click in my app.
Here is the code:
fun openDialog(cx: Context) {
val alertDialog = Dialog(cx)
var linLayout = LinearLayout(cx)
linLayout.setOrientation(LinearLayout.VERTICAL);
// Set width, height and weight
linLayout.layoutParams = LinearLayout.LayoutParams(500,1000,1F)
// top and left position
linLayout.x = 0F
linLayout.y = 0F
val title = TextView(cx); // dummy view 1
title.setText("Custom Dialog 1")
title.setTextColor(Color.BLACK)
title.setTextSize(20F)
linLayout.addView(title) // add in layout
val msg = TextView(cx) // dummy view 2
msg.setText("Custom Dialog Box 2")
msg.setTextColor(Color.RED)
msg.setTextSize(10F)
linLayout.addView(msg) // add in layout
alertDialog.setContentView(linLayout) // Add the layout in Dialog
alertDialog.show(); // Show the dialog with layout
}
What I get? A proper dialog, but in the middle of the screen with width and height defined by the content. I also try to use the windows linked to the custom dialog without success.
val wlp = win.attributes
wlp.apply {
x = 0
y = 0
height = 1000
width = 500
}
win.attributes = wlp
No changes. However wlp.gravity = Gravity.BOTTOM works, but it's not enough for me. A also try to use win.setLayout(1000,500) without success
The Android documentation states:
Set the width and height layout parameters of the window. The default
for both of these is MATCH_PARENT; you can change them to WRAP_CONTENT
or an absolute value to make a window that is not full-screen.
Why can’t I resize and position the layout that I assign to my dialog?
Has somebody a hint?
The cell phone screen:
Update
I've got to change the position of dialog using
wlp.gravity = Gravity.TOP or Gravity.LEFT
wlp.x = 100 // Relative to left
wlp.y = 200 // relative to top
I keep trying to figure out how to change the width and height.
Set the layout params for the view you're inflating when you set the content :
this line :
alertDialog.setContentView(linLayout)
should be :
alertDialog.setContentView(linLayout, LinearLayout.LayoutParams(500,1000,1F))
You can also remove the explicit setting of the params for the LinearLayout
I'm creating an AlertDialog with customized view and window background. Setting a ColorDrawable works as expected, but setting a BitmapDrawable from resources makes the dialog appear right at the top of the screen (instead of centered). (Note: I'm talking of the background behind the dialog (normally a transparent grey, not the dialog's background itself!)
Dialog background (#drawable/dialog_bg):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#color/white" />
<corners android:radius="10dp" />
</shape>
Dialog layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/dialog_bg"
android:orientation="vertical">
<!-- dialog contents -->
</LinearLayout>
Code to show dialog with ColorDrawable: -> works
private void showDialog() {
final AlertDialog dialog;
#SuppressLint("InflateParams") final ViewGroup dialogView = (ViewGroup) activity.getLayoutInflater().inflate(R.layout.my_dialog, null);
dialog = new AlertDialog.Builder(activity).setView(dialogView).create();
// this works:
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
Code to show dialog with BitmapDrawable from resources (loading a simple PNG): -> removes centering
private void showDialog() {
final AlertDialog dialog;
#SuppressLint("InflateParams") final ViewGroup dialogView = (ViewGroup) activity.getLayoutInflater().inflate(R.layout.my_dialog, null);
dialog = new AlertDialog.Builder(activity).setView(dialogView).create();
// this sets the background, but un-centers the dialog:
BitmapDrawable drawable = (BitmapDrawable) ResourcesCompat.getDrawable(activity.getResources(), R.drawable.my_bg, null);
dialog.getWindow().setBackgroundDrawable(drawable);
dialog.show();
}
Setting a ColorDrawable works as expected: The background behind the Dialog is colored and the dialog is still centered on screen.
Setting a BitmapDrawable does not work: The background is set but the dialog is moved to the top of the screen.
Things that also didn't work:
loading the drawable with ContextCompat.getDrawable() (which is the same as ResourcesCompat.getDrawable() with the current theme instead of null)
using DisplayMetrics and dialog.getWindow().getAttributes().y (and .x respectively) to calculate margins myself: (height - y) / 2 -> just returns the "normal" dialog margin
setting the gravity to CENTER on either dialog.getWindow().setGravity() or dialog.getWindow().getAttributes().gravity -> this just doesn't change anything
setting the gravity to FILL on either dialog.getWindow().setGravity() or dialog.getWindow().getAttributes().gravity -> this removes dialog margins, but still at the top (even further at the top and left, as margins are removed)
So, does anybody know how to set a background from PNG behind the dialog and keeping its centering on the screen?
We had WindowManger for Dialog to Specify custom window attributes:
The layout params you give here should generally be from values previously retrieved with {#link #getAttributes()}; you probably do not want to blindly create and apply your own, since this will blow away any values set by the framework that you are not interested in.
Just add these property according to your requirement :
/**
* Retrieve the current window attributes associated with this panel.
*
* #return WindowManager.LayoutParams Either the existing window
* attributes object, or a freshly created one if there is none.
*/
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.gravity = Gravity.TOP;
/**
* Set the width and height layout parameters of the window. The default
* for both of these is MATCH_PARENT; you can change them to WRAP_CONTENT
* or an absolute value to make a window that is not full-screen.
*
* #param width The desired layout width of the window.
* #param height The desired layout height of the window.
*
* #see ViewGroup.LayoutParams#height
* #see ViewGroup.LayoutParams#width
*/
dialog.getWindow().setLayout((int) (getScreenWidth(activity)), ViewGroup.LayoutParams.MATCH_PARENT);
dialog.getWindow().setBackgroundDrawableResource(R.drawable.message_email_selected);
/**
* Specify custom window attributes. <strong>PLEASE NOTE:</strong> the
* layout params you give here should generally be from values previously
* retrieved with {#link #getAttributes()}; you probably do not want to
* blindly create and apply your own, since this will blow away any values
* set by the framework that you are not interested in.
*
* #param a The new window attributes, which will completely override any
* current values.
*/
dialog.getWindow().setAttributes(params);
As Example :
final Dialog dialog = new Dialog(getActivity());
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_view);
// dialog.getWindow().setBackgroundDrawable(null);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setAttributes(params);
dialog.show();
//Access dialog views
TextView txt_cancel = (TextView) dialog.findViewById(R.id.txt_cancel);
So I just solved this issue, although I have to admit it's a bit hacky.
First, I disabled fading behind the dialog
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
and manually "faded" the activity by adding a view to it, overlaying the activity with semi-transparent black:
final ViewGroup dimBackgroundView = new FrameLayout(activity);
float dimAlpha = 0.5f;
dimBackgroundView.setBackgroundColor(Color.BLACK);
dimBackgroundView.setAlpha(dimAlpha);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
activityLayout.addView(dimBackgroundView, params);
This also requires me to manually darken the statusbar on supporting devices (SDK 21+):
final int statusBarColor;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
statusBarColor = activity.getWindow().getStatusBarColor();
activity.getWindow().setStatusBarColor(
Color.rgb((int) (Color.red(statusBarColor) + 255 * dimAlpha),
(int) (Color.green(statusBarColor) + 255 * dimAlpha),
(int) (Color.blue(statusBarColor) + 255 * dimAlpha)));
} else {
statusBarColor = Color.BLACK;
}
Afterwards, I added the intended background to the activity (dialogBgView on top of the semi-transparent black view) and went on adding the dialog as normal.
Since I now added all these views to the activity, I need to remove them on dialog dismissal:
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
// remove dim
activityLayout.removeView(dimBackgroundView);
// restore original statusbar color
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().setStatusBarColor(statusBarColor);
}
// remove background image
activityLayout.removeView(dialogBgView);
}
});
It works, but it's really not a nice solution. So if anyone discovers a better way, please feel free to post it here.
I have a PopupWindow which opens after I click an ImageButton:
// Get the [x, y]-location of the ImageButton
int[] loc = new int[2];
myImageButton.getLocationOnScreen(loc);
// Inflate the tag_popup.xml
LinearLayout viewGroup = (LinearLayout)findViewById(R.id.tagPopupLayout);
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = layoutInflater.inflate(R.layout.tag_popup, viewGroup);
// Create the PopupWindow
myPopupWindow = new PopupWindow(ChecklistActivity.this);
myPopupWindow.setContentView(layout);
myPopupWindow.setWindowLayoutMode(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
myPopupWindow.setFocusable(true);
myPopupWindow.setOutsideTouchable(false);
// Clear the default translucent background and use a white background instead
myPopupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.WHITE));
// Set the content of the TextViews, EditTexts and Buttons of the PopupWindow
setPopupContent(...);
// Displaying the Pop-up at the specified location
myPopupWindow.showAtLocation(layout, Gravity.NO_GRAVITY, 0, loc[1]);
because of the Gravity.NO_GRAVITY, the PopupWindow will be displayed within the borders of the Window. Everything works as intended on my Emulator, but when I run it on my Nexus 7 Tablet, it is partly covered by the Device's bottom status bar.
How can I fix this? Should I somehow get the current PopupWindow's location after the Gravity.NO_GRAVITY took place, then change the y-location to add the Device's Statusbar's height, and then re-draw it? (Will try this, but I think that having the right location to start with instead of re-drawing it is a better solution..)
This is what I came up with:
What we have:
The [x, y]-position we gave to the PopupWindow's showAtLocation-method (we only need the y-position in this, which I named oldY)
What we calculate:
The Popup height
The Status Bar height
The max possible height to be within Window boundaries (screenHeight - statusBarHeight - popupHeight)
What we then check:
We check if the oldY is larger than the maxY
If this is the case, the newY will be the maxY and we re-draw the PopupWindow. If this isn't the case it means we do nothing and just use the oldY as the correct Y-postition.
NOTE 1: I made the code for this, but during debugging it turned out the Status Bar's Height is 0 on both my Emulator and my Nexus Tablet, so just using the screenHeight - popupHeight was enough for me. Still, I included the code to calculate the Bottom Status Bar Height with a boolean in my Config-file to enable/disable this, in case the app is installed on another tablet in the future.
Here it is in code, I just added the description above to make it clear which approach I used to tackle this problem:
// Get the [x, y]-location of the ImageButton
int[] loc = new int[2];
myImageButton.getLocationOnScreen(loc);
// Inflate the popup.xml
LinearLayout viewGroup = (LinearLayout)findViewById(R.id.popup_layout);
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = layoutInflater.inflate(R.layout.popup, viewGroup);
// Create the PopupWindow
myPopupWindow = new PopupWindow(ChecklistActivity.this);
myPopupWindow.setContentView(layout);
myPopupWindow.setWindowLayoutMode(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
... // Some more stuff with the PopupWindow's content
// Clear the default translucent background and use a white background instead
myPopupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.WHITE));
// Displaying the Pop-up at the specified location
myPopupWindow.showAtLocation(layout, Gravity.NO_GRAVITY, 0, loc[1]);
// Because the PopupWindow is displayed below the Status Bar on some Device's,
// we recalculate it's height:
// Wait until the PopupWindow is done loading by using an OnGlobalLayoutListener:
final int[] finalLoc = loc;
if(layout.getViewTreeObserver().isAlive()){
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// This will be called once the layout is finished, prior to displaying it
// So we can change the y-position of the PopupWindow just before that
#Override
public void onGlobalLayout() {
// Get the PopupWindow's height
int popupHeight = layout.getHeight();
// Get the Status Bar's height
int statusBarHeight = 0;
// Enable/Disable this in the Config-file
// This isn't needed for the Emulator, nor the Nexus 7 tablet
// Since the calculated Status Bar Height is 0 with both of them
// and the PopupWindow is displayed at its correct position
if(D.WITH_STATUS_BAR_CHECK){
// Check whether the Status bar is at the top or bottom
Rect r = new Rect();
Window w = ChecklistActivity.this.getWindow();
w.getDecorView().getWindowVisibleDisplayFrame(r);
int barHeightCheck = r.top;
// If the barHeightCheck is 0, it means our Status Bar is
// displayed at the bottom and we need to get it's height
// (If the Status Bar is displayed at the top, we use 0 as Status Bar Height)
if(barHeightCheck == 0){
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0)
statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
}
// Get the Screen's height:
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenHeight = dm.heightPixels;
// Get the old Y-position
int oldY = finalLoc[1];
// Get the max Y-position to be within Window boundaries
int maxY = screenHeight - statusBarHeight - popupHeight;
// Check if the old Y-position is outside the Window boundary
if(oldY > maxY){
// If it is, use the max Y-position as new Y-position,
// and re-draw the PopupWindow
myPopupWindow.dismiss();
myPopupWindow.showAtLocation(layout, Gravity.NO_GRAVITY, 0, maxY);
}
// Since we don't want onGlobalLayout to continue forever, we remove the Listener here again
layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
NOTE 2: I've set the tag_popup itself to width = match_parent; height = wrap_content on this line:
myPopupWindow.setWindowLayoutMode(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
and the main layout of this Popup to width = match_parent; height = match_parent:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE xml>
<!-- The DOCTYPE above is added to get rid of the following warning:
"No grammar constraints (DTD or XML schema) detected for the document." -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#layout/tag_shape"
android:padding="#dimen/default_margin">
... <!-- Popup's Content (EditTexts, Spinner, TextViews, Button, etc.) -->
</RelativeLayout>
NOTE 3: My app is forced to stay in Portrait mode. I haven't test this in Landscape mode, but I assume some modifications should be made (not sure though). EDIT: Tested and it also works in Landscape mode on my two devices. I don't know if this also works in Landscape Mode with the Bottom Bar Height enabled.
Took me some time, but it works now. Hopefully they will fix PopupWindow's Gravity in the future, so it will never be below a Status bar, unless the programmer wants this themselves and change the PopupWindow's settings. Makes things a lot easier..
I'm trying to show a simple prompt dialog fragment programatically. I've extended SherlockFragmentActivity, and coded a custom SherlockDialogFragment implementation in it.
(I'm using ActionbarSherlock library, but I think the problem doesn't have to do with it, and would also be observed using regular ActionBar and Fragments).
This is the overriden oncreateDialog method inside the custom FragmentActivity class:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//Skipped section. Setting positive, negative buttons, title, message on builder.
efPsw = new EditText(getActivity());
// Hacky margin stuff (yeah, I know it's dirty)
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int smallestSide = Math.min(displaymetrics.heightPixels, displaymetrics.widthPixels);
int margin = (int)(0.5 * ((double) smallestSide));
efPsw.setTransformationMethod(PasswordTransformationMethod.getInstance());
FrameLayout fl = new FrameLayout(getActivity());
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(margin, 0, margin, 0);
fl.addView(efPsw, layoutParams);
builder.setView(fl);
return builder.create();
}
When I show the fragment, the inner framelayout is not shown (looks like an invisible rectangle that grows in height with each typed character). I'm not sure what am I doing wrong here, but certainly something must be wrong, since if I put the edittext in setView everything works fine (but without margin).
Thanks in advance.
it looks like you are making the margin half the smallest side, which in portrait mode would make your margin the entire screen. i would start by reducing the margin.
you can apply the margins directly to the EditText using the setLayoutParams() method. That would eliminate the FrameLayout.