Home > Software design >  How to link a onClick event of a button inside activity_main.xml file of a .Net Xamarin.Android proj
How to link a onClick event of a button inside activity_main.xml file of a .Net Xamarin.Android proj

Time:10-15

I'm developing my first Android App with .Net Xamarin. Doing this, I added a button and now I'm trying to get the onClick event of it.

Unfortunately, if I click on the button, I get this exception:

Java.Lang.IllegalStateException: 'Could not find method OnClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button with id 'button1''

activity_main.xml:

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@ id/button1"
    android:onClick="OnClick" />

AndroidManifest.xml:

<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true">
    <activity android:name=".MainActivity" />
</application>

MainActivity.cs:

public void OnClick(View view)
{
    ...
}

I know it's possible to add an event to the button inside the .cs file, but I'm looking for a solution defining the event inside the activity_main.xml.

Why can my App not find the OnClick method and how can I solve this issue?

CodePudding user response:

In MainActivity.cs:

Using Java.Interop;
        ...

        [Export("OnClick")]
        public void OnClick(View view)
        {
            //...
        }

You must add the reference to the Java.Interop.dll andMono.Android.Export.dll.

enter image description here

  • Related