Double tap to exit in xamarin Android

So I had to implement double tap to exit from app in Android using xamarin. This how it is implemented

  • Create blank Android App

create project

 

  • Override OnBackPressed method in MainActivity.cs
private bool doubleBackToExitPressedOnce = false;
public override void OnBackPressed()
{
if (doubleBackToExitPressedOnce)
{
base.OnBackPressed();
Java.Lang.JavaSystem.Exit(0);
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.MakeText(this, "Double tap to exit", ToastLength.Short).Show();
new Handler().PostDelayed(() =>
{
doubleBackToExitPressedOnce = false;
}, 2000);
}

view raw
MainActivity.cs
hosted with ❤ by GitHub

  • That’s it 🙂 Run the app and see the out put

double tap to exit

GIF_Maker_VideoToGif_15-3-2018_95808_PM

Thanks. 🙂

 

Toast in android using xamarin forms

 

When we want to let user know that something happening we can use Toast.

Let’s see how to create Toast in in Android in Xamarin Forms

Create xamrin foms application with Android project

project

  • In .net standard project add a Interface
public interface IToastMessageService
{
void ShowToastMessage(string message);
}

  • In Android project add ToastMessageService and implement the IToastMessageService
[assembly: Xamarin.Forms.Dependency(typeof(ToastMessageService))]
namespace ToastTestXamarin.Droid
{
public class ToastMessageService : IToastMessageService
{
public void ShowToastMessage(string message)
{
Toast.MakeText(Android.App.Application.Context, message, ToastLength.Long).Show();
}
}
}

  • In MainPage.xaml add a button
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:ToastTestXamarin"
x:Class="ToastTestXamarin.MainPage">
<Button x:Name="BtnToastMessage" Text="Show Toast" Clicked="ShowToast"></Button>
</ContentPage>

view raw
MainPage.xaml
hosted with ❤ by GitHub

  • And in the code behind implement the event handler
private void ShowToast(Object sender, EventArgs args)
{
DependencyService.Get<IToastMessageService>().ShowToastMessage("Test Toast Message");
}

view raw
MainPage.xaml.cs
hosted with ❤ by GitHub

Finally run the project 🙂

 

toast

Get the sample project on Github