为什么显示 java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27479181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why show java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String?
提问by gio
When copying String
from any browser page, pasteData
works properly.
However when copying SpannedString
from a message sent item editor(field), the application crashes and shows this error message:
String
从任何浏览器页面复制时,pasteData
工作正常。但是,当SpannedString
从消息发送项编辑器(字段)复制时,应用程序崩溃并显示以下错误消息:
java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
My code:
我的代码:
// since the clipboard contains plain text.
ClipData.Item item = clipBoard.getPrimaryClip().getItemAt(0);
// Gets the clipboard as text.
String pasteData = new String();
pasteData = (String) item.getText();
where the ClipboardManager
instance defined as clipBoard
, below:
其中ClipboardManager
实例定义为clipBoard
,如下:
clipBoard = (ClipboardManager) context.getSystemService(context.CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener(new ClipboardListener());
All I'm trying to do is use pasteData
in String
format.
How to get rid of this error?
Any help is appreciated.
所有我想要做的是使用pasteData
中String
的格式。如何摆脱这个错误?任何帮助表示赞赏。
采纳答案by Adem
SpannableString is not String directly. so, you can not cast. but, it can be converted to string. you can convert something to string with concatenating with empty string.
SpannableString 不是 String 直接。所以,你不能施法。但是,它可以转换为字符串。您可以通过连接空字符串将某些内容转换为字符串。
pasteData = "" + item.getText();
回答by gio
Returns a string with the same characters in the same order as in this sequence.
以与此序列中相同的顺序返回具有相同字符的字符串。
You need to use next code.
您需要使用下一个代码。
String pasteData = item.getText().toString();
You can not cast to android.text.SpannableString
because item.getText()
returns CharSequence
, there are a lot of implementations of it
你无法投射到android.text.SpannableString
因为item.getText()
回报CharSequence
,也有很多的实现它
回答by SilentKiller
If your Spanned text only containing HTML content then you can convert it using Html.toHtml()
如果您的跨区文本仅包含 HTML 内容,那么您可以使用 Html.toHtml()
String htmlString = Html.toHtml(spannedText);
回答by Manju S B
It has worked for meString htmlString = String.valueOf(Html.fromHtml(contenttext,Html.FROM_HTML_MODE_COMPACT));
它对我有用String htmlString = String.valueOf(Html.fromHtml(contenttext,Html.FROM_HTML_MODE_COMPACT));