I know I can set the snackbar's background by using sbView.setBackgroundColor(Color.XX);
, however, if we need to add gradient to the color instead of a single color background. What should I do? Seems no API for that.
The Snackbar does not allow you to set a custom layout. However, as Primoz990 suggested you can get the Snackbar's View. The getView function returns the Snackbar.SnackbarLayout, which is a horizontal LinearLayout object whose children are a TextView and a Button. To add your own View to the Snackbar, you just need to hide the TextView, and add your View to the 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();
In this way you can set custom layout to snackbar.
Now you can set gradient in such a way:
Create a 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>
Now apply to you custom layout as:
android:background="@drawable/my_gradient"
You may need to define a background as a shape
in drawable
folder and give it appropriate gradient as you wish lets assume this one:
Lets call it snackbar_background.xml
then:
<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>
You can explore how to make a shape in android and add a gradient to it.
Then for your snackbar
:
View snackView=snackbar.getView();
snackView.setBackgroundResource(R.drawable.snackbar_background);
And it will work fine from there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.