【问题标题】:How to make gradient in snackbar for Android?如何在 Android 的小吃店中制作渐变?
【发布时间】:2018-05-13 17:39:08
【问题描述】:

我知道我可以使用sbView.setBackgroundColor(Color.XX); 设置小吃店的背景,但是,如果我们需要为颜色添加渐变而不是单色背景。我该怎么办?似乎没有API。

【问题讨论】:

    标签: android android-snackbar snackbar


    【解决方案1】:

    您可能需要在drawable 文件夹中将背景定义为shape,并根据需要为其提供适当的渐变让我们假设:

    我们就叫它snackbar_background.xml吧:

    <shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
        <gradient
            android:startColor="#000000"
            android:centerColor="#5b5b5b"
            android:endColor="#000000"
            android:angle="0" />
    </shape>
    

    您可以探索如何制作shape in android 并为其添加渐变。

    那么为你的snackbar

    View snackView=snackbar.getView();
    snackView.setBackgroundResource(R.drawable.snackbar_background);
    

    它会从那里正常工作。

    【讨论】:

      【解决方案2】:

      Snackbar 不允许您设置自定义布局。但是,正如 Primoz990 建议的那样,您可以获得 Snackbar 的视图。 getView 函数返回 Snackbar.SnackbarLayout,它是一个水平 LinearLayout 对象,其子对象是一个 TextView 和一个 Button。要将自己的 View 添加到 Snackbar,您只需隐藏 TextView,并将您的 View 添加到 Snackbar.SnackbarLayout。

       // Create the Snackbar Snackbar      
       snackbar = Snackbar.make(containerLayout, "", Snackbar.LENGTH_LONG); 
       // Get the Snackbar's layout view 
       Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView(); 
       // Hide the text 
       TextView textView = (TextView) layout.findViewById(android.support.design.R.id.snackbar_text); 
       textView.setVisibility(View.INVISIBLE); 
       // Inflate our custom view 
       View snackView = mInflater.inflate(R.layout.my_snackbar, null); 
       // Configure the view 
       ImageView imageView = (ImageView)       
       snackView.findViewById(R.id.image); 
       imageView.setImageBitmap(image); 
       TextView textViewTop = (TextView) 
       snackView.findViewById(R.id.text); 
       textViewTop.setText(text); 
       textViewTop.setTextColor(Color.WHITE); 
       // Add the view to the Snackbar's layout 
       layout.addView(snackView, 0); 
       // Show the Snackbar 
       snackbar.show();
      

      通过这种方式,您可以为snackbar设置自定义布局。

      现在可以这样设置渐变了:

      创建一个 my_gradient.xml

       <?xml version="1.0" encoding="utf-8"?> 
       <shape 
             xmlns:android="http://schemas.android.com/apk/res/android"> 
            <gradient 
                 android:type="linear" 
                 android:angle="0" 
                 android:startColor="#f6ee19" 
                 android:endColor="#115ede" /> 
      </shape>
      

      现在将自定义布局应用为:

       android:background="@drawable/my_gradient"
      

      【讨论】:

        猜你喜欢
        • 2020-05-18
        • 2016-12-09
        • 1970-01-01
        • 2020-07-25
        • 2022-10-08
        • 2012-12-05
        • 2022-12-17
        • 2021-06-29
        • 2018-09-27
        相关资源
        最近更新 更多