如何更改Snackbar的背景颜色?

123

我正在DialogFragment中,在警报对话框的正面接触中显示snackbar。这是我的代码片段:

Snackbar snackbar = Snackbar.make(view, "Please enter customer name", Snackbar.LENGTH_LONG)
                .setAction("Action", null);
View sbView = snackbar.getView();
sbView.setBackgroundColor(Color.BLACK);
snackbar.show();

正如您所见,我的snackbar的背景颜色显示为白色

我正在将DialogFragment的视图传递给 snackbar。我想要将背景色设置为黑色。我该怎么做?我在DialogFragment中返回了alertDialog。并且我设置的对话框主题如下:

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">

    <!-- Used for the buttons -->
    <item name="colorAccent">@color/accent</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">@color/primary</item>
    <!-- Used for the background -->
    <item name="android:background">@color/white</item>
</style>

虽然我将对话框的背景色设置为白色,但通过将背景色设置为 snackbar ,它应该被覆盖。


3
http://www.technotalkative.com/part-3-styling-snackbar/ - M D
我已经尝试过了,没有帮助...我正在从对话框片段+其中的AlertDialog调用snackbar,并将正按钮单击视图传递给snackbar。 - Ajinkya
21个回答

-1
你可以在Material Design库中使用这段代码。
创建颜色代码的方法:
打开res/values/colors.xml文件,添加以下行。
<resources>
    <color name="custom_color_name">CustomCode</color>
</resources>

创建 Snackbar 并更改背景

打开您的 Activity 或 Fragment 并创建 Snackbar。

Snackbar snackbar= Snackbar.make(root,R.string.imageUploadTitle_error, BaseTransientBottomBar.LENGTH_LONG);

获取 Snackbar 视图

现在你应该获得 Snackbar 视图并在其中更改自定义背景

View snackview = snackbar.getView();

更改背景颜色

使用此函数设置 Snackbar 的背景颜色

snackview.setBackgroundColor(ContextCompat.getColor(getActivity() , R.color.error));

显示此 Snackbar

现在应该显示 Snackbar

snackbar.show();

这样你就可以看到将背景改为自定义颜色了


除了给出的解决方案,你的答案有什么新的内容? - Kishan Solanki

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