我能否在对话框中显示 Material Design Snackbar?

15

我正在开发一个安卓应用程序。我想在对话框中显示 Material Design Snackbar。这是否可能?如果是的话,怎么做?

请帮帮我。

谢谢。


从技术角度来看,这应该是一个问题。真正的问题是为什么需要那个。 - Blackbelt
我认为你不能在对话框中使用Snackbar,因为它总是显示在屏幕底部。此外,我必须说,你不应该在对话框中使用Snackbar,因为这不是正确的使用方式。 - Nooruddin Lakhani
4个回答

21

这完全是可以实现的,你只需要把对话框的视图传递给SnackBar即可。

示例

    AlertDialog.Builder mAlertDialogBuilder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    // inflate the custom dialog view
    final View mDialogView = inflater.inflate(R.layout.dialog_layout, null);
    // set the View for the AlertDialog
    mAlertDialogBuilder.setView(mDialogView);

    Button btn = (Button) mDialogView.findViewById(R.id.dialog_btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Pass the mDialogView to the SnackBar
            Snackbar
                    .make(mDialogView, "SnackBar in Dialog", Snackbar.LENGTH_LONG)
                    .show();
        }
    });
    AlertDialog alertDialog = mAlertDialogBuilder.create();
    alertDialog.show();

结果

显示结果的图片

注意: 作为根视图,没有必要使用CoordinatorLayout。在我的示例中,我只是使用LinearLayout作为根视图。


当不使用CoordinatorLayout时,可能无法滑动SnackBar。 - Paweł Nadolski

5

可以的。

要在您的Dialog中显示Snackbar,请为其创建自定义View。您可以在此处阅读有关此内容的更多信息:Dialogs/Creating a Custom Layout

然后,为了显示Snackbar,调用Snackbar.make((dialogView, "text", duration)),其中dialogView是您的自定义视图。


1
如果您正在使用一个 Dialog,那么:
dialog_share = new Dialog(MainScreen.this, R.style.DialogTheme);
dialog_share.requestWindowFeature(Window.FEATURE_NO_TITLE);
LayoutInflater inflater = this.getLayoutInflater();
mDialogView = inflater.inflate(R.layout.dialog_share, null);
dialog_share.setContentView(mDialogView);
dialog_share.getWindow().setBackgroundDrawableResource(R.color.translucent_black);
dialog_share.show();

public void ShowSnackBarNoInternetOverDialog() {
        Snackbar snackbar = Snackbar.make(mDialogView, getString(R.string.checkinternet), Snackbar.LENGTH_LONG);
        snackbar.setActionTextColor(Color.CYAN);
        snackbar.setAction("OK", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(MainScreen.this, "snackbar OK clicked", Toast.LENGTH_LONG).show();
            }
        });
        snackbar.show();
    }

1
在Snackbar.make()中使用getDialog().getWindow().getDecorView()
Snackbar
      .make(getDialog().getWindow().getDecorView(), "SnackBar in Dialog", Snackbar.LENGTH_LONG)
      .show();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接