Goe Gilber
Goe Gilber

Reputation: 51

Toast message in new item, using visual studio (Xamarin)

I made a simple program, which include TextView and Button; and every time the Button is clicked, the counter on TextView grows by 1. I also wanted that every time I click the Button, toast message will be seen.

I opened a new item in Visual Studio to do it :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V7.App;

namespace perek1_helek1_dug1_listening
{

    class Game_code : Button, Android.Views.View.IOnClickListener
    {
        private int point = 0;
        private TextView screen;

        public Game_code( TextView screen, Context context):base(context)
        {
            this.screen = screen;

        }

        public static void ShowToastMethod(Context context)
        {
            Toast.MakeText(context, "mymessage ", ToastLength.Long).Show();
        }



        public void OnClick(View v)
        {
            if (v.Id == Resource.Id.btnxml)
            {
                point++;
                **ShowToastMethod( context);**


            }
            screen.Text = "" + point;

        }


    }
}

That is How MainActivity.cs looks like:

using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;

namespace perek1_helek1_dug1_listening
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        TextView tv;
        Button btn; 

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource

            SetContentView(Resource.Layout.activity_main);

            tv = (TextView)FindViewById(Resource.Id.textboxml);
            btn = (Button)FindViewById(Resource.Id.btnxml);

            Game_code game = new Game_code(tv, this); 
            btn.SetOnClickListener(game);
        }


    }
}

However, the line :

ShowToastMethod( context);

makes the error. What should I do?

Upvotes: 0

Views: 978

Answers (2)

Goe Gilber
Goe Gilber

Reputation: 51

I googled around and found that all I had to do is change the line :

ShowToastMethod( context);

to:

ShowToastMethod(this.Context );

Thank you anyway.

Upvotes: 0

FreakyAli
FreakyAli

Reputation: 16572

I would suggest you use the events that C# has provided:

int point=0;
.
.
.
//after you find button view by ID

btn.Click+= delegate {
 tv.Text=point++;
 ShowToastMethod();
     };

public void ShowToastMethod()
    {
        Toast.MakeText(this, "mymessage ", ToastLength.Long).Show();
    }

Upvotes: 1

Related Questions