Changing position of the Dialog on screen android

2019-01-03 23:11发布

I made a simple AlertDialog in my Activity:

View view = layoutInflater.inflate(R.layout.my_dialog, null);
AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
                    .setView(view)  
                    .create();

infoDialog.show();

With above code, the dialog shows at the (about) the center of the screen.

I am wondering, how can I customize the dialog position to make it showing just under the top Action Bar ? (Is there anyway to change the gravity or something of the dialog?) and how to do it based on my code??

8条回答
The star\"
2楼-- · 2019-01-04 00:09

New BottomSheetDialog:

BottomSheetDialog dialog = new BottomSheetDialog(YourActivity.this);    
dialog.setContentView(YourView);

dialog.show();
查看更多
干净又极端
3楼-- · 2019-01-04 00:13
        public class MyDialogFragment extends DialogFragment{
     protected void setDialogGravity(int gravity) {
                Dialog dialog = getDialog();
                if (dialog != null) {
                    Window window = dialog.getWindow();
                    if (window != null) {
                        WindowManager.LayoutParams params = window.getAttributes();
                        params.width = WindowManager.LayoutParams.MATCH_PARENT;
                        params.height = WindowManager.LayoutParams.MATCH_PARENT;
                        params.horizontalMargin = 0;
                        params.gravity = gravity;
                        params.dimAmount = 0;
                        params.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
                        window.setAttributes(params);
                    }
                }
            }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);

        return inflater.inflate(R.layout.my_dialog, null);
    }

           @Override
            public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
                super.onViewCreated(view, savedInstanceState);
                setDialogGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        }
    }
查看更多
登录 后发表回答