Type cast from Java.Lang.Object to native CLR type in MonoDroid

前端 未结 8 1157
花落未央
花落未央 2021-02-02 13:38

How to cast Java.Lang.Object to some native type?

Example:

ListView adapter contains instances of native type Message. When i am trying to get SelectedItem from

相关标签:
8条回答
  • 2021-02-02 13:49

    You could always try the JavaCast<> method (most of the views implement this)(not tested):

    var message = list.SelectedItem.JavaCast< Message >();

    0 讨论(0)
  • 2021-02-02 13:49

    All of the above answers are correct but I found the simplest way for my case was to make the object a subclass of Java.Lang.Object.

    For example I'm writing a Android app in Monotouch, mimicking the concept of a UITableView in iOS using the ExpandableListAdapter, which requires the equivalent of UITableViewCells, so I subclassed cell objects from Java.Lang.Object allowing me to implement a subclass of ExpandableListAdapter such as

    public override Java.Lang.Object GetChild(int position, int childPosition)
    

    Etc.

    0 讨论(0)
  • 2021-02-02 13:50

    If for some reason GetChildAtPosition is not possible, serialise the object to json string and then deserialise the string back to native class.

    0 讨论(0)
  • 2021-02-02 13:51

    The least magical way of getting a native type from the Spinner is to call

        message = ((ArrayAdapter<Message>)list.Adapter).GetItem(list.SelectedItemPosition);
    
    0 讨论(0)
  • 2021-02-02 14:00

    After long time debuging, have found the solution:

    public static class ObjectTypeHelper
    {
        public static T Cast<T>(this Java.Lang.Object obj) where T : class
        {
            var propertyInfo = obj.GetType().GetProperty("Instance");
            return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
        }
    }
    

    Usage example:

     var message = list.GetItemAtPosition(e.Position).Cast<Message>();
     bundle.PutInt("Message", message.ID);
    

    After careful sdk study have found MonoDroid integrated extension for this purpose:

    public static TResult JavaCast<TResult>(this Android.Runtime.IJavaObject instance)
    where TResult : class, Android.Runtime.IJavaObject
    Member of Android.Runtime.Extensions
    
    0 讨论(0)
  • 2021-02-02 14:00

    For generic collections, the right answer would be to use JavaList, which is a Java.Lang.Object and also implements IList. But it involves more work that's for sure. This is actually just an adapter for Java's ArrayList implementation.

    0 讨论(0)
提交回复
热议问题