【问题标题】:Xamarin.Android: How to capture Button events defined in the OnClick XML attribute?Xamarin.Android:如何捕获 OnClick XML 属性中定义的按钮事件?
【发布时间】:2013-12-10 11:03:53
【问题描述】:

我在 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 中的不同按钮。此外,每一行都有多个按钮。

编辑:

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

【问题讨论】:

    标签: c# android xml xamarin


    【解决方案1】:

    将属性[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 公开方法,以便可以从 Java 运行时调用它。

    见:

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

    重要提示

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

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

    【讨论】:

    • 我认为现在所有开发人员都可以使用它。不过答案很好!我已经在互联网上寻找了几个小时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    相关资源
    最近更新 更多