[mono-android] Extending an activity from a java type

Jonathan Pryor jonp at xamarin.com
Tue Feb 21 17:15:33 UTC 2012


On Feb 21, 2012, at 11:56 AM, Goncalo Oliveira wrote:
> I have the need to do something like this
> 
> public class MyActivity : CrazyActivity 
> 
> Though, CrazyActivity is in a java library. Is there any way of doing this?

Yes, there is a way to do this, but it requires some "glue" code:

	Java example: https://github.com/xamarin/monodroid-samples/blob/master/SanityTests/Adder.java#L3
	C# binding example: https://github.com/xamarin/monodroid-samples/blob/master/SanityTests/ManagedAdder.cs#L6

Assuming that CrazyActivity didn't add any methods you wanted to invoke or override, binding it is fairly easy:

	[Register ("the/package/of/CrazyActivity", DoNotGenerateAcw=true)]
	class CrazyActivity : Android.App.Activity /* assuming Activity is the relevant base class */ {
		// ...
	}

If you do need to invoke methods and override virtual methods, see the above SanityTests sample, and feel free to ask additional questions. We have a work-in-progress JNI document describing how all this works; if you're going to do lots of binding, we could provide you early access to it.

If instances of CrazyActivity will be created in Java and "surfaced"/exposed to managed code, you'll also need to do two things:

1. Provide an (IntPtr, JniHandleOwnership) constructor:

	public CrazyActivity(IntPtr handle, Android.Runtime.JniHandleOwnership transfer)
		: base (handle, transfer)
	{
	}

2. Provide a type mapping between the Java type and the managed wrapper:

	Android.Runtime.TypeManager.RegisterType ("the/package/of/CrazyActivity", typeof (CrazyActivity));

The TypeManager.RegisterType() call should be performed before the Java instance is surfaced in managed code, e.g. in your app's static constructor.

Thanks,
- Jon



More information about the Monodroid mailing list