我在 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 运行时调用。
参见:
- 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/