问题 Xamarin.Android:如何捕获OnClick XML属性中定义的Button事件?


我在RelativeLayout中有这个Button,它包含在自定义ListView行Layout的一部分中。

<Button
    p1:text="Edit"
    p1:layout_width="75dp"
    p1:layout_height="wrap_content"
    p1:id="@+id/editButton"
    p1:layout_centerHorizontal="true"
    p1:background="@drawable/btn_blue"
    p1:textColor="@color/white"
    p1:focusable="false"
    p1:layout_below="@id/sparyTableLayout"
    p1:textAppearance="?android:attr/textAppearanceMedium"
    p1:onClick="myClickHandler" />

当用户单击Button时,我希望Button调用此函数:

public void myClickHandler(View v)
{
    Console.WriteLine ((v as Button).Text);
}

但是,我收到了这个错误

java.lang.IllegalStateException: Could not find a method myClickHandler(View) in the activity   class Test_Project.MyActivity for onClick handler on view class android.widget.Button with id 'editButton'

我试图区分我在ListView中的不同按钮。此外,每行有多个按钮。

编辑:

不要在按钮中使用标签,它可能会导致ListView滚动期间性能下降。以下解决方案是更好的选择。


9082
2017-11-25 16:17


起源



答案:


添加属性 [Java.Interop.Export] 到你的点击处理程序方法:

[Java.Interop.Export("myClickHandler")] // The value found in android:onClick attribute.
public void myClickHandler(View v) // Does not need to match value in above attribute.
{
    Console.WriteLine ((v as Button).Text);
}

这将通过Java将方法暴露给Java 生成的可调用包装器 对于您的活动,它可以从Java运行时调用。

看到:

  1. Mono For Android 4.2发行说明 在标题为“导出任意Java成员以实现更好的Java集成”的部分中。

重要的提示

运用 [Java.Interop.Export] 要求你添加 Mono.Android.Export 装配到您的项目。

因此,此功能仅适用于独立和更高许可证。


12
2017-11-26 07:05



我认为现在所有开发人员都可以使用它。很棒的答案!我已经在互联网上寻找了几个小时。 - Caltor


答案:


添加属性 [Java.Interop.Export] 到你的点击处理程序方法:

[Java.Interop.Export("myClickHandler")] // The value found in android:onClick attribute.
public void myClickHandler(View v) // Does not need to match value in above attribute.
{
    Console.WriteLine ((v as Button).Text);
}

这将通过Java将方法暴露给Java 生成的可调用包装器 对于您的活动,它可以从Java运行时调用。

看到:

  1. Mono For Android 4.2发行说明 在标题为“导出任意Java成员以实现更好的Java集成”的部分中。

重要的提示

运用 [Java.Interop.Export] 要求你添加 Mono.Android.Export 装配到您的项目。

因此,此功能仅适用于独立和更高许可证。


12
2017-11-26 07:05



我认为现在所有开发人员都可以使用它。很棒的答案!我已经在互联网上寻找了几个小时。 - Caltor