从Xamarin中的SpannedString获取注释

时间:2018-07-23 15:43:16

标签: xamarin.android spanned

我一直在尝试将Android example on Styling with annotations转换为C#。 Java版本如下所示(从链接中获取):

数据:

// values/strings.xml
<string name="title">Best practices for <annotation font="title_emphasis">text</annotation> on Android</string>

// values-es/strings.xml
<string name="title"><annotation font="title_emphasis">Texto</annotation> en Android: mejores prácticas</string>

代码:

// get the text as SpannedString so we can get the spans attached to the text
SpannedString titleText = (SpannedString) getText(R.string.title_about);

// get all the annotation spans from the text
Annotation[] annotations = titleText.getSpans(0, titleText.length(), Annotation.class);

// create a copy of the title text as a SpannableString.
// the constructor copies both the text and the spans. so we can add and remove spans
SpannableString spannableString = new SpannableString(titleText);

// iterate through all the annotation spans
for (Annotation annotation: annotations) {
  // look for the span with the key font
  if (annotation.getKey().equals("font")) {
    String fontName = annotation.getValue();
    // check the value associated to the annotation key
    if (fontName.equals("title_emphasis")) {
    // create the typeface
    Typeface typeface = ResourcesCompat.getFont(this, R.font.roboto_mono);
    // set the span at the same indices as the annotation
    spannableString.setSpan(new CustomTypefaceSpan(typeface),
      titleText.getSpanStart(annotation),
      titleText.getSpanEnd(annotation),
      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
  }
}

// now, the spannableString contains both the annotation spans and the CustomTypefaceSpan
styledText.text = spannableString;

我试图获得的C#版本看起来像这样

SpannedString
    spannedString = new SpannedString( GetText( Resource.String.SomeText ) );

Annotation[]
    annotations = spannedString.GetSpans( 0, spannedString.Length(), Java.Lang.Class.FromType( typeof( Annotation ) ) );

SpannableString
    spannableString = new SpannableString( spannedString );

foreach( Annotation annotation in annotations ) {
    // code
}

这应该类似于Java代码,但是由于某些原因,spannedString.GetSpans(...)返回一个空的Java.Lang.Object数组,并且注释得到null。我在这里想念什么?

0 个答案:

没有答案