UNHANDLED EXCEPTION: System.InvalidCastException: Cannot cast from source type to destination type.
06-11 19:39:01.690 I/MonoDroid(17577): at MyApp.Inbox.CorrespondenceActivity.CorrectLinkPaths (ISpanned spanText) [0x00000] in <filename unknown>:0
这是我得到的例外。使用Debug配置构建应用程序时,一切正常 - 没有例外,没有任何例外。一旦我构建它以便发布,我就会遇到这个例外 - 我无法弄清楚原因,以及如何解决它。
这是调用CorrectLinkPaths方法的代码:
_someTextView.SetText(CorrectLinkPaths(Html.FromHtml(_myMessage.Summary + "\n\n" + _myMessage.Body)), TextView.BufferType.Spannable);
毋庸置疑,_myMessage.Summary和Body是HTML字符串。
我的CorrectLinkPaths方法如下所示:
private ISpanned CorrectLinkPaths(ISpanned spanText)
{
Object[] spans = spanText.GetSpans(0, spanText.Length(), Class.FromType(typeof (Object)));
foreach (var s in spans)
{
int start = spanText.GetSpanStart(s);
int end = spanText.GetSpanEnd(s);
SpanTypes flags = spanText.GetSpanFlags(s);
if (s.GetType() == typeof (URLSpan))
{
var urlSpan = (URLSpan) s;
if (!urlSpan.URL.StartsWith("http"))
{
if (urlSpan.URL.StartsWith("/"))
urlSpan = new URLSpan("http://www.mydomain.com" + urlSpan.URL);
else
urlSpan = new URLSpan("http://www.mydomain.com/" + urlSpan.URL);
}
((ISpannable) spanText).RemoveSpan(s);
((ISpannable) spanText).SetSpan(urlSpan, start, end, flags);
}
}
return spanText;
}
有没有人知道为什么这会在调试期间有效,但是当我尝试构建发布时失败,以及如何修复它?我会非常,非常,非常感激!
谢谢:)
最好的问候。
答案 0 :(得分:2)
解决方案非常简单。方法底部的铸件导致了错误
((ISpannable) spanText).RemoveSpan(s);
((ISpannable) spanText).SetSpan(urlSpan, start, end, flags);
要解决此问题,必须将方法更改为以下内容:
public ISpanned CorrectLinkPaths(ISpanned spanText)
{
Object[] spans = spanText.GetSpans(0, spanText.Length(), Class.FromType(typeof (Object)));
ISpannable spanned = new SpannableString(spanText);
foreach (var s in spans)
{
var start = spanText.GetSpanStart(s);
var end = spanText.GetSpanEnd(s);
var flags = spanText.GetSpanFlags(s);
if (s.GetType() == typeof (URLSpan))
{
var urlSpan = (URLSpan)s;
if (!urlSpan.URL.StartsWith("http"))
{
if (urlSpan.URL.StartsWith("/"))
urlSpan = new URLSpan("http://www.mydomain.com" + urlSpan.URL);
else
urlSpan = new URLSpan("http://www.mydomain.com/" + urlSpan.URL);
}
spanned.RemoveSpan(s);
spanned.SetSpan(urlSpan, start, end, flags);
}
}
return spanned;
}
答案 1 :(得分:0)
您应该使用JavaCast,它在发布和调试模式下工作。您必须包含名称空间Android.Runtime。
spanText.JavaCast<ISpannable>().RemoveSpan(s);
spanText.JavaCast<ISpannable>().SetSpan(urlSpan, start, end, flags);