Xamarin: Determine if element in GetSpans() is bol

2019-07-23 03:16发布

问题:

Native Android Spanned.getSpans(......,SyleSpan.class) function return type StyleSpan[]

Xamarin ISpanned.GetSpans(......) function returns type Java.lang.Object[] though it returns <T> (T=StyleSpan in my case) in native android. Therefore there is a loss of information since the Mono interface doesn't expose what it would have been exposed if I had used the native SDK.

Since propery Style (getStyle() in native android) is only available in StyleSpan there is no way to read that a given StyleSpan read through GetSpans is bold or italic.

Any ideas how I determine bold or italic?

Is this a limitation in the mono interface?

回答1:

You can do everything. ;) There is just no comfortable generic wrapper for the GetSpans method.

ISpanned ss = ...;
var spans = ss.GetSpans(0, 20, Class.FromType(typeof(SyleSpan)));
foreach (SyleSpan span in spans)
{
    // do what you want
    if(span.Style == TypefaceStyle.Bold)
    {
        Debug.WriteLine("Xamarin can find bold spans, too :)");
    }
}

if you want to access it generic:

public static class ISpannedExtension
{
    public static TSpan[] GetSpans<TSpan>(this ISpanned ss, int startIndex, int length)
    {
        return ss.GetSpans(startIndex, length, Class.FromType(typeof(TSpan)))
            .Cast<TSpan>()
            .ToArray();
    }
}

// usage
ISpanned ss = ...;
var spans = ss.GetSpans<SyleSpan>(0, 20);