Press ESC to close

Xamarin Forms Toast Message

Sometimes in your applications you can request a short message on the screen. You do not have to call the user for this. When you give a message with DisplayAlert, the user has to touch the screen once again in order to pass this message. We can print the message with a Toast instead. This Toast message is so easy to use that it is a great convenience for you and your users in your application.

We will print the Toast message using dependency services. For this we need to create an interface first. I am creating an interface called IMessage. There will be two functions in this interface. These functions will run a message that stays on the screen for a long time, while the other will display a shorter message. These functions also allow you to display messages on the screen as strings from the outside.

public interface IMessage
    {
        void UzunMesaj(string mesaj);
        void KisaMesaj(string mesaj);

    }

After creating the interface we need to write dependency services for the platforms. I will do this for Android for now. For this I am going to the android layer and I am creating a class here. This class inherits from the IMessage interface we created at the portable layer. Once we inherit, we inherit functions when they are inherited. When functions come in we have to fill the inside. At the end of the message, which contexte will be the first message in the short message, we will determine the duration of the message and show it. Actually, construction is that easy. Of course, we need to specify that this class is a dependency services. We do this at the beginning of the class. If you want to get more detailed information about Dependecy Services you can get it here.

[assembly:Dependency(typeof(Mesaj_Android))]
namespace Mesaj.Droid
{
    public class Mesaj_Android : Mesaj.Helper.IMessage
    {
        public void KisaMesaj(string mesaj)
        {
            Toast.MakeText(Android.App.Application.Context, mesaj, ToastLength.Short).Show();

        }

        public void UzunMesaj(string mesaj)
        {
            Toast.MakeText(Android.App.Application.Context, mesaj, ToastLength.Long).Show();
        }
    }
}

Lastly, we need to show this on the screen. I’m pushing a button into a page. I am adding a clicked event to the button, filling it in.

private void btnTikla_Clicked(object sender,EventArgs e)
        {
            string mesaj = "Bu bir mesajdır";
            DependencyService.Get<IMessage>().UzunMesaj(mesaj);
        }

When we click on the button, the message will appear on the screen.

Click here to access the project via github. If you have any questions, you can contact me by comment or mail.

Comments (1)

Leave a Reply

Your email address will not be published. Required fields are marked *