加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Xamarin.Android:如何捕获OnClick XML属性中定义的Button

发布时间:2020-12-15 06:44:46 所属栏目:百科 来源:网络整理
导读:我把这个Button放在一个RelativeLayout里面,作为自定义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_
我把这个Button放在一个RelativeLayout里面,作为自定义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" />

当用户单击按钮时,我想要按钮调用此功能:

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

解决方法

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

看到:

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

重要的提示

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读