AlertDialog:如何删除视图上方和下方的黑色边框
收藏

之前已经有人问过这个问题:AlertDialog自定义标题带有黑色边框

但没有得到令人满意的答复-并且缺少一些信息。

我正在尝试在Android中创建一个自定义对话框,其中没有标题,并且底部没有任何按钮。

但是,结果对话框在视图的顶部和底部都有黑色的“边框” /“间距” /某物。

从文档中:

使用基础Dialog类创建的对话框必须具有标题。如果你   不要调用setTitle(),则保留标题的空间   空的,但仍然可见。如果您根本不想要标题,那么您   应该使用AlertDialog类创建自定义对话框。然而,   因为使用AlertDialog.Builder最容易创建AlertDialog   类,您无权使用所使用的setContentView(int)方法   以上。相反,您必须使用setView(View)。此方法接受一个视图   对象,因此您需要从XML扩展布局的根View对象。

所以,这就是我所做的:

Welcome.java

public class Welcome  extends Activity
{
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.welcome);

        LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.welcomedialog, (ViewGroup)findViewById(R.id.layout_root));

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(layout);
        builder.create().show();
    }
}

welcomeialog.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:background="@drawable/texturebg"
              android:id="@+id/layout_root"
              android:orientation="vertical"
              android:padding="40px">
    ...
</LinearLayout>

NOTE: I've tried using FrameLayout as the root ViewGroup instead of LinearLayout as per a suggestion I found somewhere - but that didn't help.

结果

setBackgroundDrawable建议

public class Welcome  extends Activity
{
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.welcome);

        LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.welcomedialog, (ViewGroup)findViewById(R.id.layout_root));

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(layout);
        AlertDialog dialog = builder.create();

        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));

        dialog.show();
    }
}

没为我工作。

最佳答案

If you look at the AlertDialog class source you'll see most of the methods are simply proxy methods (facade) around private AlertController mAlert.

查看AlertController类的源代码,您将看到4个有趣的成员变量:

private int mViewSpacingLeft;
private int mViewSpacingTop;
private int mViewSpacingRight;
private int mViewSpacingBottom;
private boolean mViewSpacingSpecified = false;

Setting mViewSpacingSpecified to true will remove the borders on the top and bottom of the dialog.

更改此行即可正确完成此操作:

dialog.setView(layout);

至:

dialog.setView(layout, 0, 0, 0, 0);

    公众号
    关注公众号订阅更多技术干货!