【发布时间】:2018-05-13 17:39:08
【问题描述】:
我知道我可以使用sbView.setBackgroundColor(Color.XX); 设置小吃店的背景,但是,如果我们需要为颜色添加渐变而不是单色背景。我该怎么办?似乎没有API。
【问题讨论】:
标签: android android-snackbar snackbar
我知道我可以使用sbView.setBackgroundColor(Color.XX); 设置小吃店的背景,但是,如果我们需要为颜色添加渐变而不是单色背景。我该怎么办?似乎没有API。
【问题讨论】:
标签: android android-snackbar snackbar
您可能需要在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);
它会从那里正常工作。
【讨论】:
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"
【讨论】: