c# - Xamarin.Android : How to capture Button events defined in the OnClick XML attribute?

标签 c# android xml xamarin

我在 RelativeLayout 中有这个 Button,它作为自定义 ListView 行布局的一部分包含在内。

<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 滚动期间性能下降。以下解决方案是更好的选择。

最佳答案

将属性 [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);
}

这将通过 Generated Callable Wrapper 将方法公开给 Java用于您的 Activity ,以便它可以从 Java 运行时调用。

参见:

  1. Mono For Android 4.2 release notes在标题为“为更好的 Java 集成导出任意 Java 成员”的部分中。

重要提示

使用 [Java.Interop.Export] 需要您将 Mono.Android.Export 程序集添加到您的项目中。

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

关于c# - Xamarin.Android : How to capture Button events defined in the OnClick XML attribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20197848/

相关文章:

c# - 避免使用 switch case

C#:在具有任意维度的数组中设置所有值

android - opencv4android sdk 编译器标志/ndk 版本

java - 无法实例化 Activity ComponentInfo,android使用java

java - ant "customization is not associated with any schema element"的 xjc 错误

c# - 如何使用 JSON 解析来自 google maps API 的响应?

c# - DirectoryInfo 对象可以安全地用作字典中的键吗?

Android - match_parent 忽略 layout_margin

java - JSONObject JSON 数组长度

java - Android 中两个 View 的 block 居中