Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

c# - Xamarin.Android: How to capture Button events defined in the OnClick XML attribute?

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'

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

Edit:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

See:

  1. Mono For Android 4.2 release notes within the section titled "Exporting arbitrary Java member for better Java integration".

Important Note

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

Therefore this feature is only available for Indie and higher licences.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...