How to make Dialog's width match screen width - android

I want to create a Dialog with custom layout. I want it's width to be same as the phone screen's width and height as WRAP_CONTENT.
Here is what I tried:
Dialog dialog = new Dialog(context, R.style.DialogSlideAnim);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_share);
dialog.setCanceledOnTouchOutside(true);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.copyFrom(dialog.getWindow().getAttributes());
layoutParams.width = width;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.BOTTOM;
dialog.getWindow().setAttributes(layoutParams);
The issue is that the dialog takes up only about 90% of the screen width, there is some margin on the left and right side of the dialog. How can I make it completely fill the width of the phone?

The accepted solution is simple and working, but you can also try the below solution to achieve the requirement too.
Step 1: Create Subclass of Dialog class as you want to create custom dialog.
public class ARProgressDialog extends Dialog
{
Activity context;
public ARProgressDialog(Context context,int id) {
// TODO Auto-generated constructor stub
super(context,id);
this.context=(Activity) context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.progress_dialog); // Your custom layout
// BELOW CODE IS USED TO FIND OUT WIDTH OF ANY DEVICE
DisplayMetrics displaymetrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
// BELOW CODE IS USED TO SET WIDHT OF DIALOG
LinearLayout layout = (LinearLayout)findViewById(R.id.dialogLinearLayout); // this is the id of your parent layout defined in progress_dialog.xml
LayoutParams params = layout.getLayoutParams();
params.width = width;
layout.setLayoutParams(params);
...// add your remaining code
}
}
Step 2: Show dialog.
ARProgressDialog dialog=new ARProgressDialog(this,R.style.MyTheme);
dialog.show();
Step 3: Code of MyTheme.xml
<style name="MyTheme" parent="android:Theme.Holo.Dialog">
<item name="android:windowBackground">#00000000</item>
<item name="android:backgroundDimEnabled">true</item>
</style>

This may be helpful for you:
dialog.setContentView(R.layout.my_custom_dialog);
dialog.getWindow().setBackgroundDrawable(null);
or you can try with style class like this:
<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
...
<item name="android:windowMinWidthMajor">100%</item>
<item name="android:windowMinWidthMinor">100%</item>
</style>

Related

Android - Dialog Fragment width keeps on matching parent

Good day, apologies if this seems to be a duplicate of a question that's been asked before.
I have and Android App and I am displaying a Dialog Fragment. The problem I have is that the width of the Dialog Fragment is ignored when the base activity is showing it. Here's the code in my onCreateDialog function:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = new Dialog(getActivity());
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
LayoutInflater layoutInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout2 = layoutInflater.inflate(R.layout.fragment_item_dialog, null);
dialog.setContentView(layout2);
setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialog);
Window window = dialog.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
window.setGravity(Gravity.TOP|Gravity.LEFT);
WindowManager.LayoutParams params = window.getAttributes();
params.x = 20;
params.y = 470;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.copyFrom(window.getAttributes());
window.setAttributes(params);
// -- more code here
}
and here is my xml file fragment_item_dialog
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="400dp"
android:layout_height="wrap_content" >
<!--- code here ---!>
</RelativeLayout>
The height is followed properly, but Android keeps on setting the width to match parent even though I told it to wrap content. The components inside my dialog Fragment does not exceed 400dp and I have no clue why Android is forcing my layout to match parent.
Does anyone know how to work around this? Any help is very much appreciated. Thanks.
Made it work, use the same code on onStart()
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (getDialog() == null)
return;
int width = 1100;
int height = getResources().getDisplayMetrics().heightPixels;
getDialog().getWindow().setLayout(width,
WindowManager.LayoutParams.WRAP_CONTENT);
}

Android custom AlertDialog changed width not accurate

I have a DialogFragment where I create the alertDialog in the onCreate():
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
if (alertDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
alertDialog = builder.create();
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
alertDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
}
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setView(getDialogLayout(),0,0,0,0);
return alertDialog;
}
Then I set the width (dialogWidth) of alertDialog in the onStart():
#Override
public void onStart() {
super.onStart();
WindowManager.LayoutParams lp = alertDialog.getWindow().getAttributes();
lp.width = dialogWidth;
lp.x = Constants.iX_PositionDialog;
lp.y = Constants.iY_PositionDialog;
alertDialog.getWindow().setAttributes(lp);
}
In my case i set the width of the dialog to 648 but the canvas/window of my surfaceView is just 590, why?
I need the width i set.
Set the layout after show() method of alertDialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Title");
alertDialog = builder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(648, 400); //Controlling width and height.
NOTE: Setting the layout after show() is the key point.
For more - how-to-control-the-width-and-height-of-default-alert-dialog-in-android.
To set the width and height of your alert dialouge for siffrent screen use:
int dialogWidth = getActivity().getResources().getDisplayMetrics().widthPixels-120; // screen width - whatever the width you want to set.
int dialogHeight = getActivity().getResources().getDisplayMetrics().heightPixels -140; //screen height - whatever the width you want to set.
getDialog().setCanceledOnTouchOutside(false);
Window window = getDialog().getWindow();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.gravity = Gravity.CENTER;
lp.height = dialogHeight;
lp.width = dialogWidth;
window.setAttributes(lp);
its a best practice as in andorid there are many devices and of many resolution,so we have to do everythign according to diffrent screen.so that it will be feasible with all types of screens.
I found the solution for my self.
So the alertDialog View is packed in an few FrameLayouts.
the Padding of some of these are not 0.
According of this helping code here :[AlertDialog with custom view: Resize to wrap the view's content
I make it with the following methode which i call in the onStart methode:
protected void forceWrapContent(View v) {
// Start with the provided view
View current = v;
// Travel up the tree until fail, modifying the LayoutParams
do {
// Get the parent
ViewParent parent = current.getParent();
// Check if the parent exists
if (parent != null) {
// Get the view
try {
current = (View) parent;
} catch (ClassCastException e) {
// This will happen when at the top view, it cannot be cast to a View
break;
}
// Modify the layout
current.getLayoutParams().width = dialogWidth;
current.setPadding(0, 0, 0, 0);
}
} while (current.getParent() != null);
// Request a layout to be re-done
current.requestLayout();
}
Thanks!

How to set percentage width for a dialog-themed Activity

I have an Activity with a dialog theme (Theme.Holo.DialogWhenLarge). It appears too narrow, and I'd like it to fill up a larger percentage of the screen. I am trying to accomplish this by overriding the windowMinWidthMinor and windowMinWidthMajor attributes.
The theme used by my Activity looks like this...
<style name="MyTheme" parent="#android:style/Theme.Holo.DialogWhenLarge">
<item name="android:windowMinWidthMajor">90%</item>
<item name="android:windowMinWidthMinor">90%</item>
</style>
However, it seems like the windowMinWidthMajor and windowMinWidthMinor have no effect. Can anybody explain what I'm doing wrong?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Some code here
setWindowHeight(90);
}
/**
* Set percentage width height
* #param percent percent from current size. From 0 to 100.
*/
private void setWindowHeight(int percent){
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
WindowManager.LayoutParams params = getWindow().getAttributes();
params.height = (int)(screenHeight*percent/100);
this.getWindow().setAttributes(params);
}
It's impossible to set percents for android, BUT there is a way around. What I've done is get the screen width and multiply it by the percent I want my view or item to be (example: if I want something to fill 40% of the width if would be Screen-Width * 0.4)

Setting the size of a DialogFragment

I have been trying many commands to setup the size of my DialogFragment. It only contains a color-picker, so I have removed the background and title of the dialog:
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
However I also want to position the dialog where I want and it is problematic. I use:
WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
params.width = LayoutParams.WRAP_CONTENT;
params.height = LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.LEFT;
getDialog().getWindow().setAttributes(params);
But one (big) obstacle remains: even though my dialog pane is invisible, it still has a certain size, and it limits the positions of my dialog. The LayoutParams.WRAP_CONTENT are here to limit the size of this pane to my color-picker, but for some reason it does not work.
Has anyone been able to do something similar?
i met a similar question that is you can't set the dialogFragment's width an height in code,after several try ,i found a solution;
here is steps to custom DialogFragment:
1.inflate custom view from xml on method
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().setCanceledOnTouchOutside(true);
View view = inflater.inflate(R.layout.XXX,
container, false);
//TODO:findViewById, etc
return view;
}
2.set your dialog's width an height in onResume(),remrember in onResume()/onStart(),seems didn't work in other method
public void onResume()
{
super.onResume();
Window window = getDialog().getWindow();
window.setLayout(width, height);
window.setGravity(Gravity.CENTER);
//TODO:
}
After some trial and error, I have found the solution.
here is the implementation of my DialogFragment class :
public class ColorDialogFragment extends SherlockDialogFragment {
public ColorDialogFragment() {
//You need to provide a default constructor
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_color_picker, container);
// R.layout.dialog_color_picker is the custom layout of my dialog
WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
wmlp.gravity = Gravity.LEFT;
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.colorPickerStyle);
// this setStyle is VERY important.
// STYLE_NO_FRAME means that I will provide my own layout and style for the whole dialog
// so for example the size of the default dialog will not get in my way
// the style extends the default one. see bellow.
}
}
R.style.colorPickerStyle corresponds to :
<style name="colorPickerStyle" parent="Theme.Sherlock.Light.Dialog">
<item name="android:backgroundDimEnabled">false</item>
<item name="android:cacheColorHint">#android:color/transparent</item>
<item name="android:windowBackground">#android:color/transparent</item>
</style>
I simply extend a default Dialog style with my needs.
Finally, you can invoke this dialog with :
private void showDialog() {
ColorDialogFragment newFragment = new ColorDialogFragment();
newFragment.show(getSupportFragmentManager(), "colorPicker");
}
For my use case, I wanted the DialogFragment to match the size of a list of items. The fragment view is a RecyclerView in a layout called fragment_sound_picker. I added a wrapper RelativeLayout around the RecyclerView.
I had already set the individual list item view's height with R.attr.listItemPreferredHeight, in a layout called item_sound_choice.
The DialogFragment obtains a LayoutParams instance from the inflated View's RecyclerView, tweaks the LayoutParams height to a multiple of the list length, and applies the modified LayoutParams to the inflated parent View.
The result is that the DialogFragment perfectly wraps the short list of choices. It includes the window title and Cancel/OK buttons.
Here's the setup in the DialogFragment:
// SoundPicker.java
// extends DialogFragment
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getActivity().getString(R.string.txt_sound_picker_dialog_title));
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.fragment_sound_picker, null);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.rv_sound_list);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
SoundPickerAdapter soundPickerAdapter = new SoundPickerAdapter(getActivity().getApplicationContext(), this, selectedSound);
List<SoundItem> items = getArguments().getParcelableArrayList(SOUND_ITEMS);
soundPickerAdapter.setSoundItems(items);
soundPickerAdapter.setRecyclerView(rv);
rv.setAdapter(soundPickerAdapter);
// Here's the LayoutParams setup
ViewGroup.LayoutParams layoutParams = rv.getLayoutParams();
layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = getListItemHeight() * (items.size() + 1);
view.setLayoutParams(layoutParams);
builder.setView(view);
builder.setCancelable(true);
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
// ...
});
builder.setPositiveButton(R.string.txt_ok, new DialogInterface.OnClickListener() {
// ...
});
return builder.create();
}
#Override
public void onResume() {
Window window = getDialog().getWindow();
window.setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
super.onResume();
}
private int getListItemHeight() {
TypedValue typedValue = new TypedValue();
getActivity().getTheme().resolveAttribute(R.attr.listPreferredItemHeight, typedValue, true);
DisplayMetrics metrics = new android.util.DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
return (int) typedValue.getDimension(metrics);
}
Here is fragment_sound_picker:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_sound_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
use this code for resize of Dialog Fragment android
public void onResume() {
super.onResume();
Window window = getDialog().getWindow();
window.setLayout(250, 100);
window.setGravity(Gravity.RIGHT);
}

setting a max width for my dialog

My dialog is using a linearlayout for its root, and its using the following code as its custom theme:
<style name="HuskyBusDialog">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFrame">#null</item>
<item name="android:windowBackground">#drawable/panel_background</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowAnimationStyle">#android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:colorBackgroundCacheHint">#null</item>
</style>
Is it possible to set a max width? Its fine on phones but im trying to optimize it for tablets and they are too big.
The width will be dealt with in the XML for the linear layout, not in the style that you apply to it. Use the android:layout_width tag in XML to specify how wide it could possibly be.
An old question, however no replies are suitable, but you can find some hint here: How to customize the width and height when show an Activity as a Dialog
This helps customize the width and height, but not set the max width and height! To achieve that on an activity using a dialog theme, I had to do a couple of things:
1) set a layout listener to know when the dialog layout is set.
2) Adjust the dialog layout if its size was beyond the desired limit, effectively setting max size
Here is the working snippet I'm currently using, called after setContentView():
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener()
{
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout()
{
adjustDialog();
}
});
Now the dialog size adjustment, as a percentage of actual screen size:
private void adjustDialog()
{
Window w = getWindow();
w.setGravity(Gravity.CENTER);
int current_width = w.getDecorView().getWidth();
int current_height = w.getDecorView().getHeight();
WindowManager.LayoutParams lp = w.getAttributes();
DisplayMetrics dm = getResources().getDisplayMetrics();
int max_width = (int) (dm.widthPixels * 0.90);
int max_height = (int) (dm.heightPixels * 0.90);
if (current_width > max_width)
{
lp.width = max_width;
}
if (current_height > max_height)
{
lp.height = max_height;
}
w.setAttributes(lp);
}
yeaa if u wanna do with Widht GO for ur xml
and try to do
android:layout_width="Defined in pixels//20px"
or u can try this also
android:width="Defined in pixels// 30px"
i hope it will be hepful to u

Categories

Resources