Xamarin.Android:如何捕获在onclick XML属性定义的按钮事件?按钮、属性、定义、事件

2023-09-06 02:10:00 作者:暴力小青年i

我有这个按钮,这是作为一个自定义的ListView列布局的一部分RelativeLayout的内部。

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);
}

不过,我收到此错误

However, I am getting this error

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);
}

这将暴露通过Generated可调用包装为您的活动,因此它可以在Java运行时调用。

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

请参阅:

​​单声道为Android 4.2版本说明标题为导出任意的Java成员中更好的Java集成。 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.

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