c# - 按钮 onClick 未绑定(bind)到 Activity 中的方法

标签 c# android xamarin

因此,我尝试测试将点击事件添加到我的主要 Activity 使用的 .axml 文件中的 Button。我经历了很多其他线程,并且尽我所能遵循了提供的代码。但是,当我运行我的代码时出现以下异常。

Java.Lang.IllegalStateException: Could not find method testClick(View) 
in a parent or ancestor Context for android:onClick attribute 
defined on view class android.widget.Button with id 'login'

在 Main.axml 中

  <Button
      android:text="Login"
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="2"
      android:onClick="testClick"
      android:id="@+id/login" />

在Main.cs中

public class Main : Activity
{
    protected override void OnCreate(Android.OS.Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.Main);
    }

    public void testClick(View view)
    {
        //Show alert saying clicked...
    }
}

我是否遗漏了某些配置,或者是否包含了一些配置以使其正常工作?

最佳答案

你总是可以这样做:

Button button1 = FindViewById<Button>(Resource.Id. login);
button1.Click += delegate => {
 //Show alert saying clicked...
};

如果您不想使用这种方式,您应该首先导出您的方法,如下所示查看此answer :

[Export("testClick")]
public void testClick(View view)
{
    //Show alert saying clicked...
}

如果这些不起作用,请添加对 Mono.Android.Export.dll 的引用,然后在您的 Activity 中放置此

[Java.Interop.Export("testClick")]
public void testClick(View view)
{
    //Show alert saying clicked...
}

关于c# - 按钮 onClick 未绑定(bind)到 Activity 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55050843/

相关文章:

c# - 进程 'C:\hostedtoolcache\windows\dotnet\dotnet.exe' 失败,退出代码 1

c# - 尝试使用自定义验证属性时出现 System.InvalidOperationException

android - InputConnectionWrapper 警告

Xamarin Android Javascript 和 C# 之间的双向通信

c# - 屏保如何支持多显示器?

C#,StringToEnum,我可以将它变成一个通用函数吗

android - ImageButton 中的背景颜色

android - 适用于 Android 2.2 但不适用于 Android 2.3

c# - 意外错误-Xamarin iOS

c# - 我需要添加什么才能使用 "using System.Timers;"?