在TextView中确定是否触摸了链接或纯文本,可以通过以下步骤进行:
public class LinkTextView extends TextView {
private OnLinkClickListener onLinkClickListener;
public LinkTextView(Context context) {
super(context);
}
public LinkTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LinkTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setOnLinkClickListener(OnLinkClickListener listener) {
this.onLinkClickListener = listener;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
CharSequence text = getText();
Spannable spannable = Spannable.Factory.getInstance().newSpannable(text);
int action = event.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= getTotalPaddingLeft();
y -= getTotalPaddingTop();
x += getScrollX();
y += getScrollY();
Layout layout = getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] linkSpans = spannable.getSpans(off, off, ClickableSpan.class);
if (linkSpans.length != 0) {
if (action == MotionEvent.ACTION_UP) {
linkSpans[0].onClick(this);
if (onLinkClickListener != null) {
onLinkClickListener.onLinkClick();
}
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(spannable, spannable.getSpanStart(linkSpans[0]), spannable.getSpanEnd(linkSpans[0]));
}
return true;
} else {
Selection.removeSelection(spannable);
}
}
return super.onTouchEvent(event);
}
public interface OnLinkClickListener {
void onLinkClick();
}
}
<com.example.LinkTextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your text with links here"
android:autoLink="web" />
LinkTextView textView = findViewById(R.id.textView);
textView.setOnLinkClickListener(new LinkTextView.OnLinkClickListener() {
@Override
public void onLinkClick() {
// 处理链接点击事件
}
});
通过以上步骤,你可以在TextView中确定是否触摸了链接或纯文本,并对链接点击事件进行相应的处理。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云