如何使对话框的宽度匹配屏幕宽度

How to make Dialog's width match screen width

我想创建一个带有自定义布局的 Dialog。我希望它的 width 与 phone 屏幕的宽度相同,heightWRAP_CONTENT 相同。

这是我尝试过的:

Dialog dialog = new Dialog(context, R.style.DialogSlideAnim);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_share);
        dialog.setCanceledOnTouchOutside(true);

        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        int width = metrics.widthPixels;

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(dialog.getWindow().getAttributes());
        layoutParams.width = width;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.gravity = Gravity.BOTTOM;
        dialog.getWindow().setAttributes(layoutParams);

问题是dialog只占屏幕宽度的90%左右,dialog的左右两边有一些空白。我怎样才能让它完全填满phone的宽度?

这可能对您有帮助:

dialog.setContentView(R.layout.my_custom_dialog);
dialog.getWindow().setBackgroundDrawable(null);

或者您可以像这样尝试使用 style class:

<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
    ...
    <item name="android:windowMinWidthMajor">100%</item>
    <item name="android:windowMinWidthMinor">100%</item>
</style>

公认的解决方案简单有效,但您也可以尝试以下解决方案来达到要求。

第 1 步:创建对话框 class 的子class,因为您要创建自定义对话框。

public class ARProgressDialog extends Dialog
{
    Activity context;
    public ARProgressDialog(Context context,int id) {
        // TODO Auto-generated constructor stub
        super(context,id);
        this.context=(Activity) context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.progress_dialog); // Your custom layout

        // BELOW CODE IS USED TO FIND OUT WIDTH OF ANY DEVICE 
        DisplayMetrics displaymetrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int width = displaymetrics.widthPixels;

        // BELOW CODE IS USED TO SET WIDHT OF DIALOG 
        LinearLayout layout = (LinearLayout)findViewById(R.id.dialogLinearLayout); // this is the id of your parent layout defined in progress_dialog.xml
        LayoutParams params = layout.getLayoutParams();
        params.width = width;
        layout.setLayoutParams(params);     
        ...// add your remaining code
    }

} 

步骤 2:显示对话框。

ARProgressDialog dialog=new ARProgressDialog(this,R.style.MyTheme);
dialog.show();

步骤 3: MyTheme.xml

的代码
<style name="MyTheme" parent="android:Theme.Holo.Dialog">
    <item name="android:windowBackground">#00000000</item>
    <item name="android:backgroundDimEnabled">true</item>
</style>