gpt4 book ai didi

android - TextView 可以选择并包含链接吗?

转载 作者:IT王子 更新时间:2023-10-28 23:29:00 26 4
gpt4 key购买 nike

我遇到了 TextView 的问题.我可以使用 setTextIsSelectable(true) 使其可选择,但是当我通过 setMovementMethod(LinkMovementMethod.getInstance()) 启用要单击的链接时,它不再可选择。

请注意,我的意思不是让原始链接可点击,而是通过加载 TextView 使实际单词可点击。使用类似于 setText(Html.fromHtml("<a href='http://stackoverflow.com'>Hello World!</a>")) 的 HTML 标记.

最佳答案

oakes's双击textview时回答导致异常

java.lang.IndexOutOfBoundsException: setSpan (-1 ... -1) starts before 0...

I looked at the onTouchEvent impletentation in LinkMovementMethod and found that it removes selection when textview doesn't contain link. In this case selection starts from empty value and application crash when user try to change it.

...
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(widget);
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
}
return true;
} else {
Selection.removeSelection(buffer);
}
...

所以我重写了 onTouchEvent 方法,它工作正常。

public class CustomMovementMethod extends LinkMovementMethod {
@Override
public boolean canSelectArbitrarily () {
return true;
}

@Override
public void initialize(TextView widget, Spannable text) {
Selection.setSelection(text, text.length());
}

@Override
public void onTakeFocus(TextView view, Spannable text, int dir) {
if ((dir & (View.FOCUS_FORWARD | View.FOCUS_DOWN)) != 0) {
if (view.getLayout() == null) {
// This shouldn't be null, but do something sensible if it is.
Selection.setSelection(text, text.length());
}
} else {
Selection.setSelection(text, text.length());
}
}

@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
int action = event.getAction();

if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();

x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();

x += widget.getScrollX();
y += widget.getScrollY();

Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);

ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
link[0].onClick(widget);
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
}
return true;
}
}

return Touch.onTouchEvent(widget, buffer, event);
}
}

希望对某人有所帮助。

关于android - TextView 可以选择并包含链接吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15836306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com