【问题标题】:Dialog custom layout not stretching properly对话框自定义布局未正确拉伸
【发布时间】:2015-11-06 09:55:48
【问题描述】:

我正在创建一个自定义对话框。 但它周围显示出额外的空间。

代码:

private void showPushAlert(Context context, String message, int layoutID) {
            // custom dialog
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(layoutID);

            TextView tvPushMessage = (TextView) dialog.findViewById(R.id.tvAlertMessage);
            tvPushMessage.setText(message);

            Button btnPushOk = (Button) dialog.findViewById(R.id.btnAlertOk);
            btnPushOk.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        }

布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="275dp"
    android:layout_height="wrap_content"
    android:background="@drawable/background_round_rectangle"
    android:orientation="vertical"
    android:padding="@dimen/activity_vertical_margin">
    <TextView
        android:id="@+id/tvAlertMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Message"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/black" />;
    <Button
        android:id="@+id/btnAlertOk"
        android:layout_width="65dp"
        android:layout_height="30dp"
        android:layout_below="@id/tvAlertMessage"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/btn_use"
        android:text="@string/ok"
        android:textColor="@color/white" />
</RelativeLayout>

我也试过充气机:

    final Dialog dialog = new Dialog(context);
    View view = getLayoutInflater().inflate(layoutID, null);
    dialog.setContentView(view);

但不是完美的结果。只是宽度被拉长了。 我想保持简单,所以只使用了 Dialog,而不是 AlertDialog 或 Dialog 片段。

【问题讨论】:

  • 可能有两种不同的样式试图修改布局,所以...再次检查您的样式。该空间可能来自其他样式或相对布局。尝试设置相对布局宽度 wrap_content 查看变化并尝试找出空间来自相对布局或样式?
  • 使用 'wrap_content' 作为宽度的工作方式与充气机相同。宽度伸展以适应,但上面有空间。没有注意到与“样式”相关的任何内容。

标签: android layout dialog


【解决方案1】:

不知道为什么会这样..

使用https://stackoverflow.com/a/6922903/4510869dialog.show()之后执行此操作

WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = 500;
dialog.getWindow().setAttributes(lp);

这显示了自定义宽度,但顶部空间仍然可见。 只好改成AlertDialog.Builder+上面的sn-p(AlertDialog也显示了top space)才能最终得到结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多