DialogFragment在Android中的位置

alf*_*can 60 android android-layout android-fragments android-dialogfragment

我有一个DialogFragment表现出View像一个弹出屏幕.窗口始终显示在屏幕中间.有没有办法设置DialogFragment窗口的位置?我查看了源代码,但还没找到任何东西.

Ste*_*ght 97

尝试这样的事情:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    getDialog().getWindow().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
    WindowManager.LayoutParams p = getDialog().getWindow().getAttributes();
    p.width = ViewGroup.LayoutParams.MATCH_PARENT;
    p.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;
    p.x = 200;
    ...
    getDialog().getWindow().setAttributes(p);
    ...
Run Code Online (Sandbox Code Playgroud)

或其他方法getDialog().getWindow().

请务必在调用set-content后设置位置.


Jon*_*nik 80

是的,我用头撞了一两个小时,然后最终DialogFragment像我想要的那样定位.

我正在建立在Steelight的答案上.这是我发现的最简单,最可靠的方法.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle b) {
    Window window = getDialog().getWindow();

    // set "origin" to top left corner, so to speak
    window.setGravity(Gravity.TOP|Gravity.LEFT);

    // after that, setting values for x and y works "naturally"
    WindowManager.LayoutParams params = window.getAttributes();
    params.x = 300;
    params.y = 100;
    window.setAttributes(params);

    Log.d(TAG, String.format("Positioning DialogFragment to: x %d; y %d", params.x, params.y));
} 
Run Code Online (Sandbox Code Playgroud)

请注意,params.widthparams.softInputMode(在Steelight的答案中使用)与此无关.


下面是一个更完整的例子.我真正需要的是在"源"或"父"视图旁边对齐"确认框"DialogFragment,在我的例子中是一个ImageButton.

我选择使用DialogFragment,而不是任何自定义片段,因为它为您提供免费的"对话框"功能(当用户在其外部点击时关闭对话框等).

示例ConfirmBox
示例在其"源"ImageButton(垃圾桶)上方的ConfirmBox

/**
 * A custom DialogFragment that is positioned above given "source" component.
 *
 * @author Jonik, https://stackoverflow.com/a/20419231/56285
 */
public class ConfirmBox extends DialogFragment {
    private View source;

    public ConfirmBox() {
    }

    public ConfirmBox(View source) {
        this.source = source;            
    }

    public static ConfirmBox newInstance(View source) {
        return new ConfirmBox(source);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStyle(STYLE_NO_FRAME, R.style.Dialog);
    }


    @Override
    public void onStart() {
        super.onStart();

        // Less dimmed background; see https://stackoverflow.com/q/13822842/56285
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.dimAmount = 0.2f; // dim only a little bit
        window.setAttributes(params);

        // Transparent background; see https://stackoverflow.com/q/15007272/56285
        // (Needed to make dialog's alpha shadow look good)
        window.setBackgroundDrawableResource(android.R.color.transparent);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Put your dialog layout in R.layout.view_confirm_box
        View view = inflater.inflate(R.layout.view_confirm_box, container, false);

        // Initialise what you need; set e.g. button texts and listeners, etc.

        // ...

        setDialogPosition();

        return view;
    }

    /**
     * Try to position this dialog next to "source" view
     */
    private void setDialogPosition() {
        if (source == null) {
            return; // Leave the dialog in default position
        }

        // Find out location of source component on screen
        // see https://stackoverflow.com/a/6798093/56285
        int[] location = new int[2];
        source.getLocationOnScreen(location);
        int sourceX = location[0];
        int sourceY = location[1];

        Window window = getDialog().getWindow();

        // set "origin" to top left corner
        window.setGravity(Gravity.TOP|Gravity.LEFT);

        WindowManager.LayoutParams params = window.getAttributes();

        // Just an example; edit to suit your needs.
        params.x = sourceX - dpToPx(110); // about half of confirm button size left of source view
        params.y = sourceY - dpToPx(80); // above source view

        window.setAttributes(params);
    }

    public int dpToPx(float valueInDp) {
        DisplayMetrics metrics = getActivity().getResources().getDisplayMetrics();
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
    }
}
Run Code Online (Sandbox Code Playgroud)

通过根据需要添加构造函数参数或setter,可以很容易地使上述更通用.(我的决赛ConfirmBox有一个样式按钮(在一些边框内等),其文本View.OnClickListener可以在代码中自定义.)

  • 你们摇滚 - 谢谢 - 我很好奇,**为什么我不能在片段的 XML 中设置它?** 作为一个蹩脚的 iOS 开发者,我不明白什么?谢谢男人!:) (2认同)

Aus*_*n B 5

getDialog().getWindow()不适用于DialogFragmentas,getWindow()如果看不到托管活动,则返回null;如果您正在编写基于片段的应用程序,则返回null。NullPointerException尝试时会得到一个getAttributes()

我建议Mobistry的答案。如果您已经有了DialogFragment类,则切换起来并不难。只需将onCreateDialog方法替换为构造并返回PopupWindow的方法即可。然后,您应该能够重用提供给它的View AlertDialog.builder.setView()并调用(PopupWindow object).showAtLocation()


Zah*_*sal 5

您需要在 DialogFragment 中覆盖 onResume() 方法,如下所示:

@Override
public void onResume() {
    final Window dialogWindow = getDialog().getWindow();
    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
    lp.x = 100;        // set your X position here
    lp.y = 200;        // set your Y position here
    dialogWindow.setAttributes(lp);

    super.onResume();
}
Run Code Online (Sandbox Code Playgroud)

  • 做这项工作的关键是设置一个原点。例如:Window window = getDialog().getWindow(); // 将“原点”设置为左上角,可以这么说 window.setGravity(Gravity.TOP|Gravity.LEFT); 如果不设置原点,则 x 和 y 位置将相对于屏幕中心。 (2认同)

Cil*_*ing 5

我使用AppCompatDialogFragmentfromandroid.support.v7.app.AppCompatDialogFragment并且我想将对话框片段与屏幕底部对齐并删除所有边框,特别是我需要设置内容宽度以匹配父级。

所以,我想从这个(黄色背景来自对话框片段的 rootLayout ):

src_img_1

得到这个:

src_img_2

上述解决方案均无效。所以,我这样做了:

fun AppCompatDialogFragment.alignToBottom() {
    dialog.window.apply {
        setGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL)
        decorView.apply {

            // Get screen width
            val displayMetrics = DisplayMetrics().apply {
                windowManager.defaultDisplay.getMetrics(this)
            }

            setBackgroundColor(Color.WHITE) // I don't know why it is required, without it background of rootView is ignored (is transparent even if set in xml/runtime)
            minimumWidth = displayMetrics.widthPixels
            setPadding(0, 0, 0, 0)
            layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
            invalidate()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)