[英]How to make gradient in snackbar for Android?
我知道我可以使用sbView.setBackgroundColor(Color.XX);
来设置快餐栏的背景sbView.setBackgroundColor(Color.XX);
,但是,如果我们需要为颜色添加渐变色而不是单色背景。 我该怎么办? 似乎没有API。
小吃店不允许您设置自定义布局。 但是,按照Primoz990的建议,您可以获取Snackbar的View。 getView函数返回Snackbar.SnackbarLayout,这是一个水平LinearLayout对象,其子级为TextView和Button。 要将自己的视图添加到Snackbar,只需隐藏TextView,然后将视图添加到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="@drawable/my_gradient"
您可能需要将背景定义为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>
然后为您的snackbar
:
View snackView=snackbar.getView();
snackView.setBackgroundResource(R.drawable.snackbar_background);
从那里它会正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.