Setting the size of a DialogFragment

Teovald picture Teovald · Feb 19, 2013 · Viewed 49.2k times · Source

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?

Answer

ruidge picture ruidge · Jul 29, 2013

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:
}