【问题标题】:How to change background color of the snackbar?如何更改小吃店的背景颜色?
【发布时间】:2016-03-05 09:42:32
【问题描述】:

我在警报对话框的正面触摸中以DialogFragment 显示snackbar。这是我的代码 sn-p:

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();

我正在将DialogFragment 的视图传递给小吃店。我希望背景颜色为黑色。我怎样才能做到这一点?我在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 来覆盖它。

【问题讨论】:

标签: android material-design android-dialogfragment android-snackbar


【解决方案1】:

你可以这样做

Snackbar snackbar;
snackbar = Snackbar.make(view, "Message", Snackbar.LENGTH_SHORT);
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(yourColor);
TextView textView = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(textColor);
snackbar.show();

【讨论】:

  • 如你所见,我做了完全相同的事情,但它没有显示为黑色
  • 我在我的一个项目中使用了相同的,尝试在活动中显示它以进行测试,可能由于对话框而无法正常工作
  • 它正在处理活动,但我希望它在对话框片段上。
  • 我认为是因为你的观点,你正在传递给它
【解决方案2】:

尝试像这样设置背景颜色:

sbView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.BLACK));

它将 100% 工作!

【讨论】:

  • 你可能需要做snackBarView.getView().setBackgrondColor(ContextCompat.getColor(getActivity(), R.color.BLACK));
  • 如果您发现 Google 提供的此页面及以上解决方案不适合您,您可能需要尝试此解决方案:sbView.setBackgroundColor(getResources().getColor(R.color.BLACK))
  • @modu 请注意,自 API 级别 23(棉花糖)以来,getResources#getColor 已被弃用,应改用 ContextCompat#getColor
【解决方案3】:

下面的代码可用于更改消息的文本颜色。

Snackbar snackbar = Snackbar.make(rootView, "Enter Your Message",Snackbar.LENGTH_SHORT);
View view = snackbar.getView();
TextView tv = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.RED);
snackbar.show();

第二种方式:你也可以通过改变activity的主题来改变颜色。

【讨论】:

    【解决方案4】:

    我做了一个小工具类,这样我就可以通过应用程序轻松地制作自定义颜色的小吃店。

    package com.yourapppackage.yourapp;
    
    import android.support.design.widget.Snackbar;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    public class SnackbarUtils {
    
        private int BACKGROUND_COLOR;
        private int TEXT_COLOR;
        private int BUTTON_COLOR;
        private String TEXT;
    
    
        public SnackbarUtils(String aText, int aBgColor, int aTextColor, int aButtonColor){
            this.TEXT = aText;
            this.BACKGROUND_COLOR = aBgColor;
            this.TEXT_COLOR = aTextColor;
            this.BUTTON_COLOR = aButtonColor;
        }
    
        public Snackbar snackieBar(){
            Snackbar snackie = Snackbar.make(MainActivity.getInstance().findViewById(android.R.id.content), TEXT, Snackbar.LENGTH_LONG);
            View snackView = snackie.getView();
            TextView snackViewText = (TextView) snackView.findViewById(android.support.design.R.id.snackbar_text);
            Button snackViewButton = (Button) snackView.findViewById(android.support.design.R.id.snackbar_action);
            snackView.setBackgroundColor(BACKGROUND_COLOR);
            snackViewText.setTextColor(TEXT_COLOR);
            snackViewButton.setTextColor(BUTTON_COLOR);
            return snackie;
        }
    }
    

    然后在应用程序的任何位置使用它:

    new SnackbarUtils("This is the text displayed", Color.RED, Color.BLACK, Color.YELLOW).snackieBar().setAction("OTAY", v -> { 
         //donothing
         }).show();
    

    【讨论】:

      【解决方案5】:

      把它放在一个实用程序类中:

      public class Utility {
          public static void showSnackBar(Context context, View view, String text) {
              Snackbar sb = Snackbar.make(view, text, Snackbar.LENGTH_SHORT);
              sb.getView().setBackgroundColor(ContextCompat.getColor(context, R.color.colorAccent));
              sb.show();
          }
      }
      

      这样使用:

      Utility.showSnackBar(getApplicationContext(), findViewById(android.R.id.content), "Add success!!!");
      

      【讨论】:

        【解决方案6】:
        public class CustomBar {
        
        public static void show(View view, String message, boolean isLong) {
            Snackbar s = Snackbar.make(view, message, isLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT);
            s.getView().setBackgroundColor(ContextCompat.getColor(view.getContext(), R.color.red_900));
            s.show();
        }
        
        public static void show(View view, @StringRes int message, boolean isLong) {
            Snackbar s = Snackbar.make(view, message, isLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT);
            s.getView().setBackgroundColor(ContextCompat.getColor(view.getContext(), R.color.red_900));
            s.show();
        }
        

        }

        【讨论】:

          【解决方案7】:

          为时已晚,但万一有人仍然需要帮助。这是可行的解决方案。

                Snackbar snackbar = Snackbar.make(mainView, text, Snackbar.LENGTH_LONG);
              View snackBarView = snackbar.getView();
              snackBarView.setBackgroundColor(context.getResources().getColor(R.color.btn_background_color));
              snackbar.show();
          

          【讨论】:

            【解决方案8】:

            如果您想为所有 Snackbars 定义背景颜色,只需覆盖资源中某处的 design_snackbar_background_color 值。例如:

            <color name="design_snackbar_background_color" tools:override="true">@color/colorPrimaryLight</color>
            

            【讨论】:

            • 这个解决方案最干净也很好。谢谢!
            • 效果很好,只需将其粘贴在 colors.xml 中即可!
            • 不。没有为我工作。其他解决方案也没有。
            【解决方案9】:

            Kotlin 版本(带有extension):

            在一个文件(例如 SnackbarExtension.kt)中创建一个扩展:

            fun Snackbar.withColor(@ColorInt colorInt: Int): Snackbar{
               this.view.setBackgroundColor(colorInt)
               return this
            }
            

            接下来,在您的 Activity/Fragment 中,您将能够执行此操作:

            Snackbar
              .make(coordinatorLayout, message, Snackbar.LENGTH_LONG)
              .withColor(YOUR_COLOR)
              .show()
            

            【讨论】:

            • 真的很喜欢这个答案,我也添加了文本着色: fun Snackbar.withColor(@ColorInt backgroundColor: Int, @ColorInt textColor: Int) : Snackbar { this.view.setBackgroundColor(backgroundColor) this .view.findViewById(android.support.design.R.id.snackbar_text).setTextColor(textColor) 返回这个}
            【解决方案10】:

            在使用 xamarin android 时,我发现 ContextCompat.GetColor() 返回 Int,但 setBackgroundColor() 需要颜色类型的参数。 所以这就是我如何让它在我的 xamarin android 项目中工作。

            Snackbar snackbarview =  Snackbar.Make(toolbar, message, Snackbar.LengthLong);
            View snckView = snackbarview.View;                
            snckView.SetBackgroundColor(Color.ParseColor(GetString(Resource.Color.colorPrimary)));
            snackbarview.Show();
            

            【讨论】:

            • +1 为 Xamarin View snckView = snackbarview.View; 而不是 snackbar.getView(); 不可用但 ParseColor 不起作用。
            • @Cfun 你能再解释一下你的问题,以便我可以帮助你。
            • 糟糕的是,我使用了System.Drawing.Color.ParseColor 而不是Android.Graphics.Color.ParseColor。现在我有:“名称'getstring'在当前上下文中不存在”
            • @Cfun 您是在活动或片段中收到此错误,还是在其他类中调用 getString()?
            • 我在其他类中调用它。
            【解决方案11】:

            没有其他解决方案真正适合我。如果我只设置 Snackbar 的背景颜色,TextView 和 Button 下的布局是默认颜色。如果我设置 TextView 的背景,它会在 SnackBar 显示后稍微闪烁。并且按钮周围的布局仍然是默认颜色。

            最后我发现对我来说最好的方法是更改​​ TextView 父级 (SnackbarContentLayout) 的背景颜色。现在整个 Snackbar 已正确着色,并且在显示时不会闪烁。

            snack = Snackbar.make(view, text, duration)
            View view = snack.getView();
            view.setBackgroundColor(BACKGROUND_COLOR);
            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
            tv.setTextColor(TEXT_COLOR);
            ((SnackbarContentLayout) tv.getParent()).setBackgroundColor(BACKGROUND_COLOR);
            

            【讨论】:

              【解决方案12】:

              由于没有其他答案提供自定义样式覆盖(我认为这是最安全的更新方式之一),因此我在此处发布了我的解决方案。

              我发布的解决方案已经解决了新的AndroidX (support design 28) 主题。

              假设您的应用程序在您的AndroidManifest.xml 中使用了一个名为MyAppTheme 的自定义它们:

              <application
                      android:name=".MyApplicationName"
                      android:allowBackup="true"
                      android:icon="@mipmap/icon"
                      android:roundIcon="@mipmap/icon_round"
                      android:label="@string/app_name"
                      android:theme="@style/MyAppTheme">
              

              创建(如果您还没有)values/style.xml 文件覆盖您的应用程序使用的主题:

              <style name="MyAppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
                  <item name="colorPrimary">@color/myColorPrimary</item>
                  <item name="colorPrimaryDark">@color/myColorPrimaryDark</item>
                  <item name="colorAccent">@color/myColorAccent</item>
                  <item name="snackbarStyle">@style/MySnackBarStyle</item>
              </style>
              
              <!-- snackbar style in res/values -->
              <style name="MySnackBarStyle" parent="Widget.MaterialComponents.Snackbar">
                  <item name="android:background">@color/mySnackbarBackgroundColor</item>
              </style>
              

              并在您的 values/colors.xml 文件中提供您的颜色

              <?xml version="1.0" encoding="utf-8"?>
              <resources>
                  <color name="myColorPrimary">#008577</color>
                  <color name="myColorPrimaryDark">#00574B</color>
                  <color name="myColorAccent">#D81B60</color>
                  <color name="mySnackbarBackgroundColor">#D81B60</color>
              </resources>
              

              2020 年更新

              由于上述解决方案移除了小吃店的圆角,因为这样设置背景使用了传统的小吃店设计,如果您想保留材料设计,您可以。

              1. 如果您的目标是 API 21+

              android:background 替换为android:backgroundTint

              <!-- snackbar style in res/values-21/ -->
              <style name="MySnackBarStyle" parent="Widget.MaterialComponents.Snackbar">
                  <item name="android:backgroundTint">@color/mySnackbarBackgroundColor</item>
              </style>
              
              1. 如果您的目标是 API res/values-21/ 文件夹中设置您的 MySnackbarStyle 以上并离开res/values 文件夹中的旧式风格。

              2. 如果您的目标是 API res/values/ 中更改您的小吃吧风格方式:

              <!-- snackbar style in res/values/ -->
              <style name="MySnackBarStyle" parent="Widget.MaterialComponents.Snackbar">
                  <item name="android:background">@drawable/my_snackbar_background</item>
              </style>
              

              official repo借用你的my_snackbar_background,这样:

              <!-- in res/drawable/ -->
              <shape xmlns:android="http://schemas.android.com/apk/res/android"
                  android:shape="rectangle">
                  <corners android:radius="4dp"/>
                  <solid android:color="@color/mySnackbarBackgroundColor"/>
              </shape>
              

              这是playground repo

              【讨论】:

              • 这是最干净最好的解决方案
              • 改变snakbar的大小
              • 请注意,您的 AppTheme 必须继承自 Theme.MaterialComponents 才能编译
              • 感谢my_snackbar_background。没有它,Snackbar 会用圆角绘制。
              • 我在stackoverflow.com/a/62006413/2914140 中添加了更多样式。
              【解决方案13】:

              setBackgroundResource() 也可以。

              Snackbar snackbar = Snackbar.make(view, text, Snackbar.LENGTH_LONG);
              View sbView = snackbar.getView();
              sbView.setBackgroundResource(R.color.background);
              snackbar.show();
              

              【讨论】:

                【解决方案14】:

                基本上,所提供的解决方案有一个缺点。 他们改变了小吃店的形状并移除了半径。

                就个人而言,更喜欢这样的东西

                val snackbar = Snackbar.make(view, text, Snackbar.LENGTH_LONG);
                val view = snackbar.getView();
                val color = view.resources.getColor(colorId)
                view.background.colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP)
                

                【讨论】:

                • @KishanSolanki 你可以改用this
                【解决方案15】:

                对于Material Components Library,只需使用setBackgroundTint 方法。

                    Snackbar snackbar = Snackbar.make(view, "Snackbar custom style", Snackbar.LENGTH_LONG);
                    snackbar.setBackgroundTint(ContextCompat.getColor(this,R.color.secondaryColor));
                    snackbar.show();
                


                使用 Jetpack Compose,您可以自定义 SnackbarHost,定义自定义 Snackbar

                    snackbarHost = {
                        // reuse default SnackbarHost to have default animation and timing handling
                        SnackbarHost(it) { data ->
                            Snackbar(
                                snackbarData = data,
                                backgroundColor = Color.Red
                            )
                        }
                    },
                

                那就用吧:

                scope.launch {scaffoldState.snackbarHostState.showSnackbar("Snackbar text")}
                

                【讨论】:

                  【解决方案16】:

                  我不知道为什么我的项目中没有找到 setBackgroundColor()。这就是为什么我创建了一个扩展函数,现在它很好了。

                  fun View.showSnackBar(message: String) {
                      val snackBar = Snackbar.make(this, message, Snackbar.LENGTH_LONG)
                      snackBar.setBackgroundTint(ContextCompat.getColor(this.context, R.color.colorAccent))
                      snackBar.show()
                  }
                  

                  并像下面这样称呼它

                  activity_login.xml

                  <?xml version="1.0" encoding="utf-8"?>
                  
                  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      xmlns:app="http://schemas.android.com/apk/res-auto"
                      xmlns:tools="http://schemas.android.com/tools"
                      android:id="@+id/login_holder_layout"
                      android:layout_width="match_parent"
                      android:layout_height="match_parent">
                  
                     // your UI
                  
                  </FrameLayout>
                  

                  LoginActivity.kt

                  login_holder_layout.showSnackBar("Invalid Email") 
                  

                  【讨论】:

                    【解决方案17】:

                    您可以在材料设计库中使用此代码

                    你可以用这种方式

                    创建颜色代码

                    打开 res/values/colors.xml 并添加这一行

                    <resources>
                        <color name="custom_color_name">CustomCode</color>
                    </resources>
                    

                    创建 Snackbar 并更改背景

                    打开您的活动或片段并创建 Snackber

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

                    获取 Snackbar 视图

                    现在您应该获得 SnackbarView 并在其中更改自定义背景

                    View snackview = snackbar.getView();
                    

                    改变背景颜色

                    使用此功能设置小吃栏背景颜色

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

                    显示此小吃店

                    现在应该显示 Snackbar

                    snackbar.show();
                    

                    这样您就可以看到更改为自定义颜色的背景

                    【讨论】:

                    • 除了给定的解决方案之外,您的答案有什么新变化?
                    【解决方案18】:

                    对于 Kotlin:

                    Snackbar.make(view,"simple text",Snackbar.LENGTH_SHORT).setBackgroundTint(Color.RED).show()
                    

                    【讨论】:

                      猜你喜欢
                      • 2022-11-06
                      • 2020-06-16
                      • 2015-09-13
                      • 2018-08-28
                      • 1970-01-01
                      • 2011-11-11
                      • 1970-01-01
                      • 2010-11-12
                      • 2021-06-29
                      相关资源
                      最近更新 更多