首页 > 解决方案 > 如何在按钮下方放置对话框,Android Studio?

问题描述

我将如何打开我的对话框,使其位于按钮小部件下方的设定位置?

这是我到目前为止所拥有的:

    public void showPopup(View v){

    mDialog.setContentView(R.layout.dialog_custom_workout_info);
    Window window = mDialog.getWindow();
    window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    window.setGravity(Gravity.CENTER_HORIZONTAL);
    window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    mDialog.getWindow().setDimAmount(0);
    mDialog.show();

}

对话框打开,但我只能使用重力使其居中,但我希望它在相对于另一个小部件的设定位置打开(在这种情况下,小部件被标记为“imageButton”。

提前致谢!

标签: javaandroiddialogposition

解决方案


有一个 x,y 可用于对话框的位置,您可以使用与要放置它的按钮的 x,y 的一些偏移量吗?我相信还有其他方法,但如果它有效,则对您现有的代码没有太多修改

控件的位置

            Dialog d = DialogAbout.create(this);
            Button b = findViewById(R.id.pick_button);
            // Absolute coordinates
            int[] location = new int[2];
            b.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];

           // Coordinates relative to parent
            int bx = b.getLeft();
            int by = b.getTop();

            Window window = d.getWindow();

            WindowManager.LayoutParams wlp = window.getAttributes();
            // set the new location [you will need to play with this]
            wlp.x = x;
            wlp.y = (y - b.getHeight());

            // add to your window
            window.setAttributes(wlp);

推荐阅读