Xamarin.Android:如何捕获 OnClick XML 属性中定义的按钮事件? [英] Xamarin.Android: How to capture Button events defined in the OnClick XML attribute?

查看:19
本文介绍了Xamarin.Android:如何捕获 OnClick XML 属性中定义的按钮事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this Button inside a RelativeLayout which is included as part of a custom ListView row 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" />

当用户点击按钮时,我希望按钮调用这个函数:

When the user clicks the Button, I want the Button to call this function:

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

I am trying to differentiate between the different buttons I have in that ListView. Also, each row has multiple Buttons.

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

Don't use tags in Buttons it can cause performance drop during ListView scrolling. The solution below is a better option.

推荐答案

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

Add the attribute [Java.Interop.Export] to your click handler method:

[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 运行时调用.

This will expose the method to Java via the Generated Callable Wrapper for your activity so it can invoked from the Java runtime.

见:

  1. Mono For Android 4.2 发行说明,位于标题为为更好的 Java 集成".
  1. Mono For Android 4.2 release notes within the section titled "Exporting arbitrary Java member for better Java integration".

重要提示

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

Important Note

Using [Java.Interop.Export] requires you to add the Mono.Android.Export assembly to your project.

因此,此功能仅适用于独立和更高级别的许可证.

这篇关于Xamarin.Android:如何捕获 OnClick XML 属性中定义的按钮事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆