others-how to expand BottomSheetDialog to full width of the screen in android ?

1. Purpose

In this post, I will demonstrate how to expand BottomSheetDialog to full width of the screen in android.

2. Solution

2.1 Original code: trying to build a dialog in android:

MyDialog MyDialog = new MyDialog(this);
MyDialog.setContentView(R.layout.dialog_my);
MyDialog.show();

Here is the not working code(not full width):

final MyDialog bottomSheetDialog = new MyDialog(this);
        bottomSheetDialog.show();

The above code shows a dialog that is not fully horizontally displayed in the screen.

In the dialog initialize the content as follows:

public class MyDialog extends BottomSheetDialog {
    
    ...

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

        setContentView(R.layout.dialog_my);
        findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyDialog.this.cancel();
            }
        });

    }
    ...
}

2.2 Solution to this problem: change onCreate of the dialog:

        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

So the full width BottomSheetDialog is as follows:

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

        setContentView(R.layout.dialog_my);
        findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyDialog.this.cancel();
            }
        });

        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
    }

Not it works!



3. Summary

In this post, I demonstrated how to expand BottomSheetDialog to full width of the screen, the core point is to set the layout params for the dialog window . That’s it, thanks for your reading.