简体   繁体   中英

Visual Studio / Xamarin OnClickListener

I'm new to programming, so I apologise if this is a stupid question! I'm building an app in VS15/Xamarin, and am trying to set an onClickListener, however it keep stelling me there is an error "The type name 'OnClickListener' does not exist in the type 'View'". I've tried a number of solutions, but clearly I'm missing something! This is my code:

    using System;
    using Android.App;
    using Android.Content;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;

    namespace MyStory
    {
        [Activity(Label = "MyStory", MainLauncher = true, Icon = "@drawable/Books")]
        public class MainActivity : Activity
        {


        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            Button btn_Short = FindViewById<Button>(Resource.Id.btn_Short);
            Button btn_Flash = FindViewById<Button>(Resource.Id.btn_Flash);
            Button btn_Poet = FindViewById<Button>(Resource.Id.btn_Poet);
            Button btn_About = FindViewById<Button>(Resource.Id.btn_About);

            btn_About.SetOnClickListener(new View.OnclickListener())
            {
                @override
                public void onClick(View v)
                {
                    startActivity(new Intent(MainActivity.this, About.class));
                }
            }
        }        
    }
}

This is what the screen looks like:

screenshot

C# is not java.Try something like this:

btn_About.Click += myCustomClick;

Then outside your oncreate:

public void myCustomClick(object o, EventArgs e) {
//handle click here
}

But check the syntax.

If you want it your way you should make your activity implement View.IOnClickListener like this:

public class MainActivity: Activity, View.IOnClickListener
{
 //code here
}

Question was asked very long ago but I found it and so may others. Hope this helps somebody.

Xamarin has its newances and using += EventHandler has its dangers. Firstly you must be sure to unregister this handler at the end of the object's lifecycle as otherwise it will cause memory leaks. Using Androids ClickListener is really a better solution. In Xamarin you can do something like this

public class TEditClickListener : Java.Lang.Object, View.IOnClickListener
{
    private RelayCommand _command;

    public TEditClickListener(RelayCommand command)
    {
        _command = command;
    }

    public void OnClick(View v)
    {
        _command?.Execute(null);
    }
}

and then instantiate this class and use View.SetOnClickListener method to register it. This way there surely won't be memory leaks.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM