26

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?

Teovald
  • 4,369
  • 4
  • 26
  • 45
  • 1
    Size and position of the Dialog need to be set inside the Dialog constructor. You have to override onCreateDialog of DialogFragment and where you have to create a custom Dialog. – Sudar Nimalan Feb 19 '13 at 00:15
  • 1
    +Sudar Nimalan Thanks, that was a part of the solution. – Teovald Feb 22 '13 at 16:46
  • 3
    For future readers, related questions: 1) [Setting the size (width and height) of DialogFragment](http://stackoverflow.com/questions/12478520/how-to-set-dialogfragments-width-and-height) 2) [Positioning DialogFragment](http://stackoverflow.com/questions/9698410/position-of-dialogfragment-in-android) – Jonik Feb 26 '14 at 20:20

4 Answers4

47

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:
}  
ruidge
  • 1,149
  • 1
  • 15
  • 14
  • This worked for me too. For some reason my top/bottom margins were being ignored, but I changed it to padding and it worked for me. – SilithCrowe Apr 07 '14 at 19:15
  • The code in `onResume()` can also work in `onCreateDialog()` for those who are already using that method for various other dialog hacks. – Richard Le Mesurier Sep 01 '14 at 14:58
  • Works great. It works withOUT any of the customization in onCreateView.. Just the Window stuff in onResume() is fine. – nat101 May 25 '16 at 04:40
  • Really genius. Keep up nice work. Just for curiosity want to know why this problem occurs on few devices & not on others? – VVB Jan 17 '17 at 11:39
  • i think the width and height depends on screen size but i cant really find the pattern because i am facing problem when setting size to dialogfragment. if i set the height 150 and if the get the height of the fragment it is giving me other answers. please help me in this question https://stackoverflow.com/questions/45494644/how-to-set-the-height-of-the-dialog-fragment-accurately-in-android – Aman Verma Aug 03 '17 at 22:52
22

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");
   }   
Teovald
  • 4,369
  • 4
  • 26
  • 45
  • thank you so much! I would like to ask you what did you do about position the dialog where you want? Could you do that and how? – Jorge Gil Apr 15 '13 at 17:23
  • 1
    In onCreateView, you can also access the parameters of the layout with : WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes(); . Then for example if you want to put the dialog on the left side of the screen, you just need to use wmlp.gravity = Gravity.LEFT; then wmlp.x = this.getResources().getDimensionPixelOffset(R.dimen.dialog_position); – Teovald Apr 15 '13 at 21:27
  • 1
    ... except how does this let you set the width of the dialog? – Richard Le Mesurier Sep 01 '14 at 14:50
5

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>
Ari Lacenski
  • 631
  • 12
  • 18
3

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);
    }
murthy10
  • 156
  • 4
  • 12
Mahi Saini
  • 219
  • 2
  • 2
  • i think the width and height depends on screen size but i cant really find the pattern because i am facing problem when setting size to dialogfragment. if i set the height 150 and if the get the height of the fragment it is giving me other answers. please help me in this question https://stackoverflow.com/questions/45494644/how-to-set-the-height-of-the-dialog-fragment-accurately-in-android – Aman Verma Aug 03 '17 at 22:53