我知道我可以使用sbView.setBackgroundColor(Color.XX);
设置小吃栏的背景,但是,如果我们需要为颜色添加渐变而不是单色背景。我该怎么办?似乎没有API。
答案 0 :(得分:1)
Snackbar不允许您设置自定义布局。但是,正如Primoz990建议您可以获得Snackbar的视图。 getView函数返回Snackbar.SnackbarLayout,它是一个水平的LinearLayout对象,其子对象是TextView和Button。要将自己的视图添加到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();
通过这种方式,您可以将自定义布局设置为小吃栏。
现在您可以通过以下方式设置渐变:
创建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=
&#34; @可绘制/ my_gradient&#34;
快乐的编码 如果需要更多帮助,请告诉我
答案 1 :(得分:1)
您可能需要在shape
文件夹中将背景定义为drawable
,并根据您的意愿为其提供适当的渐变:
让我们称之为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);
它会在那里正常工作。