你好,我在文本视图中设置了一些文本。
TextView tweet = (TextView) vi.findViewById(R.id.text);
tweet.setText(Html.fromHtml(sb.toString()));然后,我需要将TextView的文本转换为Spannble。所以我就这样做了:
Spannable s = (Spannable) tweet.getText();我需要将它转换为Spannable,因为我将TextView传递给了一个函数:
private void stripUnderlines(TextView textView) {
Spannable s = (Spannable) textView.getText();
URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
for (URLSpan span : spans) {
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
s.removeSpan(span);
span = new URLSpanNoUnderline(span.getURL());
s.setSpan(span, start, end, 0);
}
textView.setText(s);
}
private class URLSpanNoUnderline extends URLSpan {
public URLSpanNoUnderline(String url) {
super(url);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
}这没有显示错误/警告。但是抛出一个运行时错误:
java.lang.ClassCastException: android.text.SpannedString cannot be cast to android.text.Spannable如何将文本视图的SpannedStringt/text转换为Spannble?或者我可以在函数中使用SpannedString执行同样的任务吗?
发布于 2013-07-26 13:20:38
如何将文本视图的SpannedStringt/text转换为Spannble?
new SpannableString(textView.getText())应该能工作。
或者我可以在函数中使用SpannedString执行同样的任务吗?
对不起,removeSpan()和setSpan()是Spannable接口上的方法,SpannedString不实现Spannable。
发布于 2016-01-14 20:34:12
这应该是正确的工作。虽然很晚了,但将来可能有人需要它。
private void stripUnderlines(TextView textView) {
SpannableString s = new SpannableString(textView.getText());
URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
for (URLSpan span : spans) {
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
s.removeSpan(span);
span = new URLSpanNoUnderline(span.getURL());
s.setSpan(span, start, end, 0);
}
textView.setText(s);
}
private class URLSpanNoUnderline extends URLSpan {
public URLSpanNoUnderline(String url) {
super(url);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
}发布于 2016-02-26 18:56:26
不幸的是,所有这些都不适合我,但在你的所有解决方案之后,我发现了一些有用的东西。
除非将textView.getText()指定为Spannable,否则它将错误地将其转换为SPANNABLE
还请注意@CommonsWare的页面:
请注意,您不希望在TextView上调用TextView(),因为您认为将用修改后的版本替换文本。您正在此fixTextView()方法中修改TextView的文本,因此不必使用setText()。更糟糕的是,如果您正在使用android:autoLink,setText()将导致Android返回并再次添加URLSpans。
accountAddressTextView.setText(accountAddress, TextView.BufferType.SPANNABLE);
stripUnderlines(accountAddressTextView);
private void stripUnderlines(TextView textView) {
Spannable entrySpan = (Spannable)textView.getText();
URLSpan[] spans = entrySpan.getSpans(0, entrySpan.length(), URLSpan.class);
for (URLSpan span: spans) {
int start = entrySpan.getSpanStart(span);
int end = entrySpan.getSpanEnd(span);
entrySpan.removeSpan(span);
span = new URLSpanNoUnderline(entrySpan.subSequence(start, end).toString());
entrySpan.setSpan(span, start, end, 0);
}
}https://stackoverflow.com/questions/17882077
复制相似问题