Snackbar provides a non intrusive way to notify a user about something. It can also be used to initiate an action with a clickable button on the snackbar itself. Snackbar is a really useful and effective material design UI element.
This post contains all the code that’s been written in this YouTube video.
You can also check out this GitHub repository: https://github.com/ResoCoder/SnackbarXamarinAndroid
MainActivity.cs
using Android.App; using Android.Widget; using Android.OS; using Android.Support.V7.App; using Android.Support.Design.Widget; namespace SnackbarTut { [Activity(Label = "SnackbarTut", MainLauncher = true)] public class MainActivity : AppCompatActivity { CoordinatorLayout rootView; static TextView actionText; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); rootView = FindViewById<CoordinatorLayout>(Resource.Id.root_view); actionText = FindViewById<TextView>(Resource.Id.action_text); FindViewById<Button>(Resource.Id.btn_show_snackbar).Click += (sender, e) => { var snackbar = Snackbar.Make(rootView, "I'm a snackbar!", Snackbar.LengthLong) .SetAction("Click Me", v => actionText.Text = "Snackbar was clicked!"); snackbar.AddCallback(new MySnackbarCallback()); snackbar.Show(); }; } class MySnackbarCallback : Snackbar.Callback { public override void OnDismissed(Snackbar transientBottomBar, int @event) { base.OnDismissed(transientBottomBar, @event); if (@event != DismissEventAction) actionText.Text = "Placeholder text"; } } } }
Main.axml
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/root_view"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="vertical"> <Button android:id="@+id/btn_show_snackbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="20dp" android:text="Show Snackbar" /> <TextView android:id="@+id/action_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="Placeholder text" android:textSize="25sp"/> </LinearLayout> </android.support.design.widget.CoordinatorLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="SnackbarTut.SnackbarTut" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="21" /> <application android:allowBackup="true" android:label="@string/app_name" android:theme="@style/Theme.AppCompat"> </application> </manifest>
how can I add snackbar at top of the screen?