Xamarin: Determine if element in GetSpans() is bold or italic?

家住魔仙堡 提交于 2020-01-16 05:08:15

问题


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


来源:https://stackoverflow.com/questions/38079662/xamarin-determine-if-element-in-getspans-is-bold-or-italic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!